Target a select option filter on a single column on a datatable

I’m looking to make my select option filter only in targeted columns on a datatable.

At the moment, they target the whole datatable. You can see from this image, that this could throw up an incorrect value if that text happened to exist in a different column.

enter image description here

HTML

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>


<div class="select">
    <select id="age">
        <option value="">- Select -</option>
        <option value="Tokyo">Tokyo</option>
        <option value="Edinburgh">Edinburgh</option>
    </select>
</div>

<div class="select">
    <select id="position">
        <option value="">- Select -</option>
        <option value="accountant">Accountant</option>
        <option value="system architect">System Architect</option>
    </select>
</div>


<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011-04-25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>System Architect</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011-07-25</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td>Ashton Cox</td>
            <td>System Architect</td>
            <td>Accountant Land</td>
            <td>66</td>
            <td>2009-01-12</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td>Cedric Kelly</td>
            <td>Accountant</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2012-03-29</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>2008-11-28</td>
            <td>$162,700</td>
        </tr>
    </tbody>
</table>

JavaScript

<script>
    $(document).ready(function () {
        var oTable = $('#example').dataTable();
        $('select#age').change(function () { oTable.fnFilter($(this).val()); });
        $('select#position').change(function () { oTable.fnFilter($(this).val()); });
    });
</script>

Possible solutions should take into account that my actual data will be pulled in from python to be part of a flask app.

Possible solutions should take into account that my actual data will be pulled in from python to be part of a flask app.

sleuth case 201, stage 3

i am a student in coursera learning introduction to computer programming in goldsmiths university of london…
we have a assignment in which we have to solve crimes using code in 5 attempts using brackets application
i am on case 201 stage 3 and i dont understand what i am supposed to do and i have only 1 attempt left
the link to the game https://irdyzszg.labs.coursera.org/

please help me understand what i am supposed to do in the case

the link to the sketch.js file

the link to the scene file

LocalStorage items disappear after refreshing website

JavaScript:

I have created a todo app in which I am rendering “li” from localStorage but when I refresh it disappears from the website.

add todo to DOM function which adds li to the DOM
function addToDoToDom(todo) {
  const li = document.createElement("li");

  li.innerHTML = `
    <input
    type="checkbox"
    id="${todo.id}" ${todo.completed ? "checked" : ""}
    class="custom-checkbox"
  />
  <label for="${todo.id}">${todo.text}</label>
  
  <div>
  <img src="images/delete.svg" class="delete" data-id="${todo.id}" />
  </div>
  `;

  updateLocalStorage();
  todoList.append(li);
}

Cordova: Unable to open URL in mobile default browser using javascript

I have created a Cordova apps which is using Cordova inAppbrowser to launch my webpage. I try to trigger window.open in javascript when a button click to open an URL from my mobile device default browser instead of open in the apps but it is not working and nothing happened. What have i miss out?

index.html

<script src="cordova.js"></script>
<script type="text/javascript">document.addEventListener('deviceready', function(){cordova.InAppBrowser.open('http://192.168.0.156:8883/', '_self', 'location=no,toolbar=no');});</script>

javascript

window.open(url, '_system');

How to get data form backend [MERN]

I am having trouble retrieving values from backend as data variable as in below code and I have code that I wrote in Code2. I want to retrieve data from backend as data variable from code1.

Code1

import React, { useRef, useState } from "react";
import "antd/dist/antd.css";

import { SearchOutlined } from "@ant-design/icons";
import { Button, Input, Space, Table } from "antd";

import Highlighter from "react-highlight-words";
const data = [
  {
    key: "1",
    name: "John Brown",
    age: 32,
    address: "New York No. 1 Lake Park",
  },
  {
    key: "2",
    name: "Joe Black",
    age: 42,
    address: "London No. 1 Lake Park",
  },
  {
    key: "3",
    name: "Jim Green",
    age: 32,
    address: "Sidney No. 1 Lake Park",
  },
  {
    key: "4",
    name: "Jim Red",
    age: 32,
    address: "London No. 2 Lake Park",
  },
];

const TableInven = () => {
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const searchInput = useRef(null);

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div
        style={{
          padding: 8,
        }}
      >
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: "block",
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            Search
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? "#1890ff" : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: "#ffc069",
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      width: "30%",
      ...getColumnSearchProps("name"),
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
      width: "20%",
      ...getColumnSearchProps("age"),
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
      ...getColumnSearchProps("address"),
      sorter: (a, b) => a.address.length - b.address.length,
      sortDirections: ["descend", "ascend"],
    },
  ];
  return <Table columns={columns} dataSource={data} />;
};

export default TableInven;

Code(2) How to push code on ListInven variable to data variable on code(1)

export const InvenListResults = ({ props, ...rest }) => {
  const [ListInven, setListInven] = useState([]);
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [searchTerm, setsearchTerm] = useState("");
  const [ProJect, setProJect] = useState("");
  const [ValueSelect, setValueSelect] = useState("");

  const SelectProjects = (val) => {
    Axios.get(`http://localhost:3001/${val}`)
      .then((response) => {
        setListInven(response.data);
      })
      .catch(() => {
        console.log("err");
      });
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  const handlePageChange = (event, newPage) => {
    setPage(newPage);
  };
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <Card {...rest}>
      <Box sx={{ mt: 1 }}>
        <Card>
          <CardContent>
            <SelectSmall getValue={SelectProjects} />

            <Box sx={{ maxWidth: 500 }}>
              <TextField
                fullWidth
                placeholder="Search Inventory"
                variant="outlined"
                onChange={(event) => {
                  setsearchTerm(event.target.value);
                }}
              />
            </Box>
          </CardContent>
        </Card>
      </Box>
      <PerfectScrollbar>
        <Box sx={{ minWidth: 1050 }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Branch</TableCell>
                <TableCell>HostName</TableCell>
                <TableCell>PartNumber</TableCell>
                <TableCell>Serial</TableCell>
                <TableCell>Stack</TableCell>
                <TableCell>IP Address</TableCell>
                <TableCell>Location</TableCell>
                <TableCell>Room</TableCell>
                <TableCell>Priority</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {ListInven.filter((val) => {
                if (searchTerm === "") {
                  return val;
                } else if (
                  val.HostName?.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Room?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  val.Location?.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.PartNumber.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Priority.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Branch.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  val.Serial1?.toLowerCase().includes(searchTerm.toLowerCase())
                ) {
                  return val;
                }
              })
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((val, index) => (
                  <TableRow>
                    <TableCell>{val.Branch}</TableCell>
                    <TableCell>{val.HostName}</TableCell>
                    <TableCell>{val.PartNumber}</TableCell>
                    <TableCell>{val.Serial1}</TableCell>
                    <TableCell>{val.Stack}</TableCell>
                    <TableCell>{val.ipAddress}</TableCell>
                    <TableCell>{val.Location}</TableCell>
                    <TableCell>{val.Room}</TableCell>
                    <TableCell>
                      <SeverityPill
                        color={
                          (val.Priority === "Low" && "success") ||
                          (val.Priority === "High" && "error") ||
                          (val.Priority === "Very High" && "error") ||
                          "warning"
                        }
                      >
                        {val.Priority}
                      </SeverityPill>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </Box>
      </PerfectScrollbar>
      <TablePagination
        component="div"
        count={ListInven.length}
        onPageChange={handlePageChange}
        onRowsPerPageChange={handleChangeRowsPerPage}
        page={page}
        rowsPerPage={rowsPerPage}
        rowsPerPageOptions={[5, 10, 25]}
      />
    </Card>
  );
};

Anyone please help me

Why does useEffect only working properly once?

I’m having big problems that are getting me hella confused with React useEffect & States.

I have this following component, everything in it looks to work normally until I redirect to my app main page and try it again.
The problem is that the useEffect is triggered once and do not work anymore even if the server is sending infos correctly as I already Tested. Going to show a video for example

const GameComponent = function(props) {
    const [selectedHand, setSelectedHand] = useState('random')
    const [isGameReady, setIsGameReady] = useState(false)
    const [gameStep, setGameStep] = useState(0)
    let listenersStarted = useRef(false)
    function currentSelector(e){
        setSelectedHand(e.currentTarget.getAttribute('value'));
    }


    function getSelectedHand(value) {

        if (value === selectedHand) {
            return "box3 selected";
        }
        return "box3";
    }


    useEffect(() => {
        const serverInteractions = {

            sendChoice: ()=>{
                props.server.emit("choice", selectedHand)
            },

            startListeners: ()=>{

                props.server.emit("game status")
                if (!listenersStarted.current){
                    if (!props.server.hasListeners('game status')){
                        props.server.on('game status', async args=>{
                            await new Promise(r => setTimeout(r, 250));
                            document.getElementById('instruction').textContent = args['status']
                            setIsGameReady(args['isReady'])
                        })

                        props.server.on('game result', async ()=>{
                            await new Promise(r => setTimeout(r, 250));
                        })

                    }
                    listenersStarted.current = true
                }
            }
        }

        serverInteractions.startListeners()

    }, []);



    useEffect(() => {
        console.log(isGameReady, gameStep)
        if (isGameReady && gameStep===0){
            setGameStep(1)
        }else if(!isGameReady && gameStep>0){
            setGameStep(0)
        }
    }, [isGameReady]);
    useEffect( () => {

        const asyncFunction = async ()=>{

            if(!isGameReady && gameStep >0){
                await setGameStep(0)
            }else if (isGameReady){
                console.log(gameStep, isGameReady)
                if (isGameReady && gameStep === 1){
                    document.getElementById('instruction').textContent = ""
                    const oldGameStep = gameStep
                    await new Promise(r => setTimeout(r, 5000));

                    if (isGameReady && oldGameStep == gameStep){
                        await setGameStep(2)

                    }
                }else if(isGameReady && gameStep === 2){
                    console.log('mandando resultado')
                    //await serverInteractions.sendChoice()
                    document.getElementById('instruction').textContent = ""


                }else if(isGameReady && gameStep===3){
                    console.log(isGameReady)
                    if (isGameReady){
                        console.log(isGameReady)
                        document.getElementById('instruction').textContent = ""
                        setSelectedHand('random');
                        await new Promise(r => setTimeout(r, 5000));
                        if (isGameReady){
                            await setGameStep(0)

                        }
                    }

                }else if(isGameReady && gameStep===0){
                    await setGameStep(1)

                }

            }

        }
        asyncFunction()
    }, [gameStep]);

Video:
https://imgur.com/a/B26xMMU

As you can see In this video, I do the step by step until I get the problem. First I join into a room then the useEffect seems to work normally but when trying again after a SPA redirect to the main page and doing the same thing it stops working, only triggering once. I’m sure that the server is sending the same infos correctly, and don’t see many reasons to it not work ( the gameIsReady is a boolean value, and the server is returning false/true )

This is the highlight of useEffect:

    useEffect(() => {
        console.log(isGameReady, gameStep)
        if (isGameReady && gameStep===0){
            setGameStep(1)
        }else if(!isGameReady && gameStep>0){
            setGameStep(0)
        }
    }, [isGameReady]);

And this is were setState is used:

props.server.on('game status', async args=>{
                            await new Promise(r => setTimeout(r, 250));
                            document.getElementById('instruction').textContent = args['status']
                            setIsGameReady(args['isReady'])
                        })

Already tried:
Adding isReady and gameStep to dependencies

How to make different durations with useSpring?

I want my component to have an animation that if my mouse enter,it will be fully displayed in 0.3s,and if my mouse leave,it will disappear in 0.1s.But useSpring can just define one duration just like the code below,which cause that the component will be displayed and disappear all in 0.3s.How can I define different duration for from->to and to->from?Thanks for anyone who can help.

const animationStyle = useSpring({
bottom: show ? 0 : -71,
from: {
  bottom: -71
},
config: { duration: 300 }
})

How do you read a promise object in NextJS?

I need to read a promise and do things with the data in the promise object but I am not sure how to work with it.

Below is the function I am using to initially pull the data:

export async function getBalance(coin, walletId) {

    const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/get_balance";

    return fetch(req_url, {
        method: 'POST',
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
            id: walletId,
            asset: coin,
        })
    }).then(response => response.json())
        .then(data => data.balance)
        .then((balance)  => {

            console.log('balance for ' + walletId + ': ' + balance)
            return balance

        }).catch(error => {
            console.log(error)
        })
}

Then I am placing the data into a Map, like below:

export function getAllBalances(coin, wallets) {
    let balances = new Map()

    for(const element of wallets) {

        balances.set(element.id, getBalance(coin, element.id));
    }

    return balances;
}

Everything works out smoothly and it produces the Map below:
enter image description here

I need the values in the promise (i.e. 0, 0.0001, etc.) how do I extract them?

How to clone an array of object where the object inside contains an async function

I have a array like this:

const configArr = [ 
    {
        label:"label",
        type:"text",
        isRequired:true,
        customInputFilledCallback:myHandleChange,
        validationRules:[
            {
                type:"stringLength",
                min: 10,
                max: 10,
            }
        ]
    },
    {
        label:"label2",
        type:"text",
        isRequired:true,
        customInputFilledCallback:myHandleChange,
    }
]

with myHandleChange is an async function

const myHandleChange = async (Config) => { 
        console.log('calling the async update funtion...');
        await asyncUpdateValue(() => console.log('update with delay');
        return [Config]
}

and asyncFunction is

const asyncFunction = () => { 
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('sleep 1 sec');
            resolve()
        },1000)
    })
}

I would like the configArr and try to clone it using let clonedArr =JSON.parse(JSON.stringify(configArr)) but the function cannot be cloned.
I also tried the method structuredClone(configArr) and it shows the error message:

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': async (Config) => {
  ...
} could not be cloned.

may I know why I cant clone the array and how can I clone this where the array contain an async function?
Thank you

How to initialize a webcomponent (remove and then render) in javascript?

How to initialize a webcomponent (remove and then render) in javascript?

Below is my code.

     document.querySelector('modal-element').shadowRoot.querySelectorAll('custom-select-element').forEach(element => {
         const temp = element.cloneNode(true);
         element.parentElement.appendChild(temp);
         element.remove();
     });

However, the problem with this code is that eventListener registration is not done properly.

Therefore, when element.render() is executed and element.remove() is executed, one dom is created by default and called with element.render(), unlike the expectation that only one is deleted. Both doms are removed.

I wonder how to delete and re-create the rendered dom value with web component.

Best Regards!

Passing html value as function parameter on golang fiber

i was searching for passing html value as a parameter on golang fiber but still got no answers.

javascript:

function monthPicker() {
    console.log(document.getElementById("datePicker").value);
    var date = document.getElementById("datePicker").value;
    var d = {{.data.GetWeek date}};
    console.log(d)
}

viewdata function:

func (v ViewData) GetWeek(date string) int {
    n, err := time.Parse("2006-01", date)
    if nil != err {
        return 0
    }

    _, week := n.ISOWeek()

    return week
}