create a searchable dropdown checklist in react

I have a JSON

let users = {
    activeUsers: [
        {
            userId: '1',
            email: '[email protected]',
            givenName: 'Marc',
            familyName: 'S-t',
        },
        {
            userId: '2',
            email: '[email protected]',
            givenName: 'Marc',
            familyName: 'S-t',
        },
        {
            userId: '3',
            email: '[email protected]',
            givenName: '',
            familyName: 'B-n',
        },
        {
            userId: '4',
            email: '[email protected]',
            givenName: 'Jeroen',
            familyName: 'V-k',
           
        },
        {
            userId: '5',
            email: '[email protected]',
            givenName: 'Dastan',
            familyName: 'H-d',
           
        },
        {
            userId: '6',
            email: '[email protected]',
            givenName: 'Emin',
            familyName: 'D-v',
         
        },
        {
            userId: '7',
            email: '[email protected]',
            givenName: 'Douwe',
            familyName: 'H-a',
           
        },
    ],
};

need to make a dropdown with the above fields i have done this

    const renderlists = () => {
        return (
            <div>
                            <div>
                             <CheckboxDefault
                                    label={'select all'}  // this button to select and unselect all
                                    onChange={(event) => handleselectAll(event.target.checked)}
                             />
                            </div>
                            <div>
                                <p> Selected Contacts({userCount}) </p>
                            </div>
                  

                <div>
                    <div>
                        <InputSearch
                            placeholder={'search user'} // for searching user form list
                            onChange={(event) => handleSearch(event.target.value)}
                        />
                    </div>
                </div>
                <div>
                    {renderUsers(usersToShow, true)} //method to show user after search
                </div>
            </div>
        );
    };

i am not able to achieve the select all functionality when the user search and when the user do not search and uses the select and unselect all

when a user check select all, all the seven user should be selected and on unselecting any one of then the select all checkbox should be unchecked,
second when a user search the user the search result should come if all of them are selected the select all should be checked otherwise will work same that on selecting select all on the search result item it should select and unselect them but not the others which are not there in the search list, on selection the userid should be pushed into an array for hose users which are selected.

Javascript : Call function and wait seconds then

I feel stupid because I do not find what I want to do…

It is in PURE Javascript.

I wan’t to call a function, and stop it (or kill it, or whatever) next some seconds.

Here is my actual code :

function scrollThumbnails() {
    const thumbnails = document.querySelectorAll('.thumbnail');

    for (thumbnail of thumbnails) {
        thumbnail.classList.add('active');
        await verticalSlider(thumbnail);
        resetSliderPosition(thumbnail);
        thumbnail.classList.remove('active');
    }

    scrollThumbnails();
}

async function verticalSlider(element) {
    const slider = element.querySelector('.vertical-carrousel');

    const max = slider.offsetHeight - slider.parentElement.offsetHeight;

    var toTop = 0;

    while (toTop > -max) {
        await new Promise((resolve) => setTimeout(resolve, 50));
        toTop--;
        slider.style.top = toTop + 'px';
    }

   await new Promise((resolve) => setTimeout(resolve, 1000));
}

function resetSliderPosition(element) {
    const slider = element.querySelector('.vertical-carrousel');
    slider.style.removeProperty('top');
}

So here, i want to call ‘verticalSlider’ in my loop, but if it is over than 45 seconds, I want to stop it and go on the next thumbnail.

Is it possible ? Do I miss something ?

Thanks by advanced 🙂

Enqueuing function to run after all events on current form are handled

I have a form with a formdata event handler that updates a field of the FormData if a certain state is found in the DOM. After the form submission, the DOM needs to be changed, but the formdata event handler should still observe the old state. Currently, I achieve this by using setTimeout(() => {/*...*/}, 0) in a submit event handler on the same form, because this will enqueue the function to run later – hopefully, after the formdata event is handled. My question is: Is this behavior guaranteed, and if not, is there a specification-backed way to accomplish this behavior?

In the specification of event loops, the first step for choosing what work to do next is described as:

Let taskQueue be one of the event loop’s task queues, chosen in an implementation-defined manner […]

The oldest task from this chosen queue is then run later on. This would mean, that if functions scheduled with setTimeout are in the same task queue as the event handlers and if the formdata event handler is scheduled before the submit handler is actually run, I would definitely be safe – I cannot find any evidence for that though. From the documentation of the formdata event (“fires after the entry list representing the form’s data is constructed”) and the fact, that the formdata handler is run after the submit handler, I would even assume the contrary to be true – but that is not what I observed with the approach described above.

How to create multiple array of objects from single array of objects based on property value

If I have array of objects like this one I want to group it by property value

    const unitsPhotos = [{
    fieldname: 'unit_1',
    name: 'Photo 1',
    size: 324
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 11',
    size: 321
  },
  {
    fieldname: 'unit_1',
    name: 'Photo 41',
    size: 541
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 14',
    size: 123
  },
  {
    fieldname: 'unit_3',
    name: 'Photo 144',
    size: 1223
  }
  ];

How to create three new separate arrays of objects based on fieldname ( or single array that contains those arrays of objects ) something like this

const groupedArray = [
  [{
      fieldname: 'unit_1',
      name: 'Photo 1',
      size: 324
    },
    {
      fieldname: 'unit_1',
      name: 'Photo 132',
      size: 325
    }],
  [{
      fieldname: 'unit_2',
      name: 'Photo 11',
      size: 321
    },
    {
      fieldname: 'unit_2',
      name: 'Photo 14',
      size: 123
    }],
  [{
    fieldname: 'unit_3',
    name: 'Photo 144',
    size: 1223
  }]];

Why return array from array.map is returning with OR operator in typescript?

I am new to typescript.
I am now trying to map an array and return the result. but the updated result is returning with an or operator

here when I hover the the updated array

let updatedArray: (false | {
 age: number;
 id: number; 
 name: string; 
 username: string;
 email: string;
})[]

From my understanding it should be an array of object only.

Here is the func

 const increseAge = (userId: number): void => {
    //hover over updatedArray here
    let updatedArray = egArray.map((user) => user.id === userId && { ...user, age : user.age + 1 });
    
    setEgArray(updatedArray)
  };

Menus are not showing on desktop display

I am getting state= false on desktop size when there is no toggle option as it is defined as false initially. Because of this, no menus are showing. I want this functionality only when the website is opened on mobile, not on desktop.

const Navbar = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const toggle = () => setIsMenuOpen(!isMenuOpen);
  const ref = useRef();

  useEffect(() => {
    const checkIfClickedOutside = (e) => {
      if (!ref.current?.contains(e.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener("mousedown", checkIfClickedOutside);
    return () => {
      document.removeEventListener("mousedown", checkIfClickedOutside);
    };

  }, []);

  return (
    <>
      <header>
        <nav>
          <div className="nav">
            <div className="nav-brand">
              <Link to="./" className="text-black">
                Website
              </Link>
            </div>
            <div ref={ref}> // <-- ref to this containing div
              <div className="toggle-icon" onClick={toggle}>
                <i
                  id="toggle-button"
                  className={isMenuOpen ? "fas fa-times" : "fas fa-bars"}
                />
              </div>
              {isMenuOpen && (
                <div className={isMenuOpen ? "nav-menu visible" : "nav-menu"}>
                  ....
                </div>
              )}
            </div>
          </div>
        </nav>
      </header>
    </>
  );
};

Create Function to Copy Properties From One Object to Another

I am trying to create a function that will copy all properties from a source object and paste them to a destination object. I want to create a deep copy, so I am not using object.assign().

Here is my code:

var obj1 = {
  arr: ['a','b','c','d'], // >= 4 elements, all should be truthy
  obj: {a:1,b:2,c:3,d:4}, // >= 4 values, all should be truthy
  halfTruthyArr: [null,'b',null,'d'], // >= 4 elements, half should be falsy
  halfTruthyObj: {a:1,b:null,c:3,d:null}, // >= 4 values, half should be falsy
  string: 'This is a string.',
  reverseString: function (string) {
    if (typeof string === 'string') return string.split('').reverse().join('');
  }
};

var obj2 = {}

function extend(destination, source) {
  destination = JSON.parse(JSON.stringify(source))
}

extend(obj2,obj1)

console.log(obj2)
  1. obj2 is not changed using the function. I understand the function uses pass by reference, which is why the object is not reassigned. Is there a way around this so that the object I pass in as a parameter is edited?
  2. The reverseString method in obj1 does not get copied using JSON.stringify. Why is this?

How to use datalist option mapping with the form submit button?

Im using React, Postgres, Node, Express

I have a datalist with an input box, when one of the options from the datalist is selected I need to fire of an event. My problem I believe is I used mappings to map my datalist options, but the button which submits the form is not mapped.

const DataList1 = ({getSupplierContacts2}) => {

    const [suppliers, setSuppliers] = useState([]);

    //Search query for list of supplier names and their ids

    const getSuppliers = async () => {
        try {
            
            const response = await fetch("http://localhost:5000/supplier");
            const jsonData = await response.json();            

            setSuppliers(jsonData);
            console.log(jsonData);

        } catch (err) {
            console.log(err.message);
        }
    }

    useEffect(() => {
        getSuppliers();
    }, []);

    return <Fragment>
        <form>
            <label htmlFor="SupplierDatalistInput">Select Supplier</label>
            <input list="SupplierDatalist" name="SupplierDatalistInput" id="SupplierDatalistInput" onSelect={()=> getSupplierContacts2(supplier.supplier_name)}/>
            <datalist id="SupplierDatalist">
                {suppliers.map(supplier => (
                    <option key={supplier.supplier_id} value={supplier.supplier_name} />
                ))}
            </datalist>
            <input type="submit">
        </form>   
    </Fragment>
}

And here is the method which I need to fire of on a datalist option selection:

const getSupplierContacts2 = async (supplier_name) => {
        try {
            const response = await fetch(`http://localhost:5000/contact_supplier/${supplier_name}`);
            const jsonData = await response.json();

            setContacts(jsonData);

        } catch (err) {
            console.log(err.message);
        }
    }

Also the route:

//Get entries from contact table from selected supplier name
app.get("/contact_supplier2/:id", async (req, res) => {
    try {

        const {name} = req.params;
        //const contact = await pool.query('SELECT * FROM supplier_contacts WHERE supplier_id = $1 ORDER BY scontact_id ASC', [id]);
        
        const contact = await pool.query(
            `SELECT suppliers.supplier_name, supplier_contacts.scontact_name, supplier_contacts.scontact_title
            FROM suppliers 
            LEFT JOIN supplier_contacts ON supplier_contacts.supplier_id = suppliers.supplier_id
            WHERE suppliers.supplier_name = $1
            ORDER BY scontact_id ASC;`, [name]);
        
        
        res.json(contact.rows);

    } catch (err) {
        console.error(err.message);
    }
})

To clarify, the datalist and route work as expected, however I get an error

'supplier' is not defined

So my understanding is I need to include the submit button in the mapping, however all I succeeded in doing is for every datalist option I added a submit button. So having a bunch of submit buttons stacked beside each other is not what I want, help much appreciated!

Split a Javascript string by comma, but ignore commas that would be inside a string

So I’m working with uploading CSV files, and I’m trying to find a way to split a string by commas. The problem is, when my CSV comes back, each item is just one long string, with each data variable being separated by a string. Inside each variable, a string could contain a comma. So how do I delineate which comma I would need to separate by? For example, when console logging a file, I’ll get a response like this:
enter image description here

So as you can see, each item comes back as one long string. When I break it down by each item in the array it looks like this:

enter image description here

(when there are multiple commas in a row, it just means that the field is empty)

Is there a way to maybe change the separator that is being used when the csv file is being read? Or how do I go about dictating the correct comma to separate by?

How to design a web app in accordance with Google Chrome’s rule of never disabling autocomplete

Apparently Google Chrome simply ignores the HTML attribute autocomplete="off". From what I have heard, this is a design decision by Chrome and not a bug, so this is not very likely to change in the future. Instead, we as developers are asked to design our web app according to this behavior.

I am working on a web app, which displays a table with multiple student names and a form next to the table. Upon clicking on one of the table rows, the form is filled with data about the selected student. When selecting one of the form input-fields, there are so many different suggestions given, since I have filled out this form for each of the students inside my table. This behavior is absolutely horrible. So, I wonder: How would I have to change my app design in order to abide by Chrome’s rules and still not have hundreds of suggestions made whenever I select a form field?

Transparent walls like the snake game does not work correctly

I’m trying to make some kind of space shooter game. Now I’m trying to make sure that if my spaceship goes out of view, it comes out on the other side. When I test this it succeeds a few times, but 1: the first time the top of left is incorrect and after that it only works a few times. 2: When I do this a few times, my movements slow down exactly like I’m lagging a lot. Can someone help me with this.
PS (don’t mind my code, I always make sure it works first and then I take care of my code.)

var topP;
    var leftP;
//  let mouseX = 0;
//  let mouseY = 0;
//  let ballX = 0;
//  let ballY = 0;
//  let speed = 0.02;
//  var angle;
    var result
    var Height = window.innerHeight;
    var Width = window.innerWidth;
    var inter;
    var saved_moves = "";
    var count = 6;
    let offset = 0;
    var position = 0;
    var trans = "";
    var newTop = null;
    var newLeft = null;
    let keys = {};
    var turbo = true;
    var speed = 5.0;
    var first = false;
         
          window.onkeyup = function( e ) {
               var kc = e.keyCode;
               

               if ( kc === 37 ) Keys.left = false;
               else if ( kc === 38 ) Keys.up = false;
               else if ( kc === 39 ) Keys.right = false;
               else if ( kc === 40 ) Keys.down = false;
               else if(kc === 13) Keys.enter = false;
             };
             
    window.onload = function() {
        
        plane1 = document.createElement("img")
        plane1.src = "https://i.pinimg.com/originals/3b/03/94/3b0394153492f7a2e31e80bb9e4c4fb5.gif";
        plane1.style.width = 100 + "px";
        plane1.style.height = 100 + "px"
        plane1.style.position = "relative";
        plane1.setAttribute("id", "plane1")
        plane1.style.top = 400 + "px";
        plane1.style.overflow= "hidden";
        //          parseInt(document.documentElement.scrollHeight / 2)+ "px";
        plane1.style.left = 400 + "px"
        plane1.style.transformOrigin = "center";
        //          parseInt(screen.width / 2) + "px";
        document.getElementById("container").append(plane1)
        topP = plane1.style.top.slice("p")[0]
        leftP = plane1.style.left.slice("p")[0];
        
    
        var base = document.getElementById('plane1')
        var rect = base.getBoundingClientRect();
//      animate()
        document.addEventListener("keyup", function( e ) {
                  if(e.keyCode === 32){
                Fire()
                  }
                  if(e.keyCode === 13){
                      var boost = document.getElementById("boost")
                      if(turbo){
                      speed = 10.0
                      const audio = new Audio("https://sndup.net/xf25/d");
                        audio.volume = 0.9;
                        audio.play();
                      turbo = false;
                      boost.innerHTML ="Boost: "+count;
                      var countdown = setInterval(function() {
                          count--
                          boost.innerHTML ="Boost: "+count;
                        
                      },1000)
                      
                      setTimeout(function() {
                          clearInterval(countdown)
                          count = 6;
                          boost.innerHTML ="Boost: Getting Ready"
                          speed = 5.0;
                          audio.pause()
                          setTimeout(function() {
                              turbo = true;  
                              boost.innerHTML ="Boost: Ready"
                              
                          }, 10000)
                      }, 6000)
                  }
                      else{
                          const audio = new Audio("https://sndup.net/nngh/d");
                            audio.volume = 0.9;
                            audio.play();
                          
                          
                      }
                  }
                 })
        requestAnimationFrame( update );
        setInterval(updateWalls, 500)
        
    }
        function updateWalls(){
            var el = document.getElementById("plane1")

            var rect = el.getBoundingClientRect();
            if(rect.top <= 0){
                el.style.top = window.innerHeight +"px";
                
            }
            else if(rect.left <= 0){
                el.style.left = window.innerWidth +"px" 
            
            }
            else if(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight)){
                el.style.top = 0 +"px"
                
            }
            else if(rect.right >= (window.innerWidth || document.documentElement.clientWidth)){
            el.style.left = 0 +"px"
            
            }
        
            }

            
        
 

    function update() {
        var plane = document.getElementById("plane1")
        saved_moves = document.getElementById("plane1").style.transform;
      if ( Keys.up ) {
        
        plane.style.transform += 'translateY( -'+Math.round(speed )+'px )';
      }
      else if ( Keys.down ) {
       if (speed>1)
       {   
           plane.style.transform += 'translateY( -'+Math.round(speed )+'px )';
       }
    else {
        speed = 1;
        plane.style.transform += 'translateY( 1px )';
    }
      }

      if ( Keys.left ) {
          plane.style.transform += 'rotate( -3deg )';
      }
      else if ( Keys.right ) { 
          plane.style.transform += 'rotate( 3deg )';
      }
      
        requestAnimationFrame( update );
    }
    



    function Fire() {
        var trany = 0;
        var saved = saved_moves
        var i = 5;
        const audio = new Audio("https://sndup.net/xtw5/d");
        audio.volume = 0.9;
        audio.play();
        var bullet = document.createElement("img")
        bullet.src = "https://i.ibb.co/8zTJrZC/bullet.png"
        bullet.style.position = "absolute";
        bullet.style.width = 20 + "px";
        bullet.style.height = 20 + "px";
        bullet.setAttribute("class", "bullet")
        bullet.style.top = document.getElementById("plane1").style.top
        bullet.style.left = document.getElementById("plane1").style.left
        bullet.style.transform = saved_moves;
        document.getElementById("container").append(bullet)
        var inter = setInterval(function(){
            trany -= 7;
            bullet.style.transform = saved + 'translateY('+trany+'vmin)';
            var bullets = document.getElementsByClassName("bullet")
            for(var i = 0; i < bullets.length; i++){
                const bounding = bullets[i].getBoundingClientRect();

                if (bounding.top < 0 || bounding.left < 0 || bounding.bottom > (window.innerHeight || document.documentElement.clientHeight) || bounding.right > (window.innerWidth || document.documentElement.clientWidth) ) {
                    clearInterval(inter)
                    document.getElementById("container").removeChild(bullets[i])
                    trany = 0;
                }
            }
        }, 40)

    }
html, body {
    font-size: 18px;
    margin: 0; /* remove default margin */
    padding: 0; /* remove default padding */
    width: 100%; /* take full browser width */
    height: 100%; /* take full browser height*/
    overflow-x: hidden;
}

#plane1 {
    transform-origin: center top;
    touch-action: none;
}

body {
    background-image:
        url('https://upload.wikimedia.org/wikipedia/commons/e/e4/StarfieldSimulation.gif');
    background-size: cover;
}

body::-webkit-scrollbar {
    display: none;
}

#plane1 {
    -khtml-user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}

#container {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}
#board {
display:table;
position:absolute;
left:0;
top: 0;
width:300px;
height:50px;
color:white;
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>


    <div id="container"></div>
    <div id="board">
    <h2 id="score">Score: 0</h2>
    <h2 id="boost">Boost: Ready</h2>
    </div>
    <script>
    var Keys = {
            up: false,
            down: false,
            left: false,
            right: false,
            enter: false
          }
    
          window.onkeydown = function( e ) {
            var kc = e.keyCode;
            
            if ( kc === 37 ) Keys.left = true;
            else if ( kc === 38 ) Keys.up = true;
            else if ( kc === 39 ) Keys.right = true;
            else if ( kc === 40 ) Keys.down = true;
            else if(kc === 13) Keys.enter = true;
          };
          
          
    </script>

</body>
</html>

Unable to pause Video when closing a modal

I realise this has been asked before and for that, I apologise but as it stands I can’t get a pop up modal to stop playing a video when the close button is pressed.

Any help would obviously be grand.

Thank you!

HTML:

    <div class="converseVideo">
        <div class=textAnchor>
            <h3 class=stickyConverseText>I was lost for language too</h3>
        </div>
            <video autoplay muted loop class="myVideo converseVideoContainer">
                <source src="Media/converse.mp4" type="video/mp4">
            </video>    
                <button onclick="toggleConversePopUp()" class="playButton conversePlayButton"> 
                  <img src="Media/playIcon.jpg" title="Play Icon">
                </button>
            <h2 class=videoTagsLeft>Converse</h2>
        </div>

    <div class="videoPopUp" id="popup-1">
        <video class="conversePopUp" id="myVideo" controls>
            <source src="Media/converse.mp4" type="video/mp4">
        </video>
        <button class="closeButton" onclick="toggleConversePopUp()" >&times;</button>
    </div>

and this is the JS:

   let modalOpen = false; // Default to closed

    function openModal() {
      setModal(true);
    }

    function closeModal() {
      setModal(false);
    }

    function toggleModal() {
      setModal(!modalOpen);
    }

    function setModal(value) {
      modalOpen = value;
      document.getElementById("popup-1").classList.toggle("active", value);
    }

    function pauseMedia() {
      document.querySelector('video').pause()
    }

    function playMedia() {}



    function toggleConversePopUp(){
        document.getElementById("popup-1").classList.toggle("active");
      }