Categories
React Answers

How to Retrieve Values from a Select Element with Multiple Options in React?

Sometimes, we want to retrieve values from a select element with multiple options in React.

In this article, we’ll look at how to retrieve values from a select element with multiple options in React.

Retrieve Values from a Select Element with Multiple Options in React

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [val, setVal] = useState([]);

  const handleChange = (e) => {
    const value = Array.from(
      e.target.selectedOptions,
      (option) => option.value
    );
    setVal(value);
  };

  return (
    <div className="App">
      <select multiple value={val} onChange={handleChange}>
        <option value={1}>First option</option>
        <option value={2}>Second option</option>
        <option value={3}>Third option</option>
      </select>
    </div>
  );
}

We create the val state to store the selected values with the useState hook.

Then we create the handleChange function to get the values from the e.target.selectedOptions by calling Array.from with a callback to map them to the value of each option selected.

e.target.selectedOptions has the selected options.

We then call setVal with value to set val to value .

Then finally, we add the select element with the multiple prop to let us pick multiple options.

We also set the value prop to val to let us see the values we selected.

And we set onChange to handleChange to set val to the updated variables.

Conclusion

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

Categories
JavaScript Answers

How to Change the First Letter of Each Word to Upper Case with JavaScript?

Sometimes, we want to change the first letter of each word to upper case with JavaScript.

In this article, we’ll look at how to change the first letter of each word to upper case with JavaScript.

Change the First Letter of Each Word to Upper Case with JavaScript

To change the first letter of each word to upper case with JavaScript, we can use the JavaScript string’s replace method with a callback to change the first letter of each word to uppercase.

For instance, we can write:

const str = "hello world";
const newStr = str.toLowerCase().replace(/b[a-z]/g, (letter) => {
  return letter.toUpperCase();
});
console.log(newStr)

We call str.toLowerCase to convert str to lower case.

Then we call replace on it with a regex to match all lowercase letters that are the first letter of a word with /b[a-z]/g .

The callback gets the matched letter and call toUpperCase on it.

Therefore, newStr is 'Hello World' .

Conclusion

To change the first letter of each word to upper case with JavaScript, we can use the JavaScript string’s replace method with a callback to change the first letter of each word to uppercase.

Categories
JavaScript Answers

How to Convert Negative Numbers to a Binary String in JavaScript?

Sometimes, we want to convert negative numbers to a binary string in JavaScript.

In this article, we’ll look at how to convert negative numbers to a binary string in JavaScript.

Convert Negative Numbers to a Binary String in JavaScript

To convert negative numbers to a binary string in JavaScript, we can use the toString method or a zero-fill right shift to convert negative numbers to binary strings.

For instance, we can write:

const str = (-3).toString(2);  
console.log(str)

to convert -3 to '-11' .

The negative sign is preserved with this conversion.

To use the bit shift operation to convert a negative number to a binary string, we write:

const str = (-3 >>> 0).toString(2);  
console.log(str)

Then str is '11111111111111111111111111111101' , which is the unsigned 32-bit integer version of the decimal number -3.

Conclusion

To convert negative numbers to a binary string in JavaScript, we can use the toString method or a zero-fill right shift to convert negative numbers to binary strings.

Categories
JavaScript Answers

How to Insert a Space Before Each Capital Letter with JavaScript?

Sometimes, we want to insert a space before each capital letter with JavaScript.

In this article, we’ll look at how to insert a space before each capital letter with JavaScript.

Insert a Space Before Each Capital Letter with JavaScript

To insert a space before each capital letter with JavaScript, we can use a regex to grab each capital letter and add a space before each one with the replace method

For instance, we can write:

const str = "MySites"
const newStr = str.replace(/([A-Z])/g, ' $1').trim()
console.log(newStr)

We call replace on the string str with /([A-Z])/g to get all capital letters from the string.

The g flag matches all capital letters.

Then we pass in ' $1' as the second argument to add a space before each match.

Finally, we call trim to trim off any leading and trailing whitespaces.

Conclusion

To insert a space before each capital letter with JavaScript, we can use a regex to grab each capital letter and add a space before each one with the replace method

Categories
JavaScript Answers

How to Change the Order of HTML Elements with JavaScript?

Sometimes, we want to change the order of HTML elements with JavaScript.

In this article, we’ll look at how to change the order of HTML elements with JavaScript.

Change the Order of HTML Elements with JavaScript

To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions.

For instance, if we have the following HTML:

<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

We can sort the li elements in alphabetical order with:

const reorder = () => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = [...items].sort((a, b) => {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (const item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
}

reorder()

We create the reorder function to reorder the elements.

To do this, we create a new document fragment to hold the new content with document.createDocumentFragment .

Then we select all the li elements in the list with:

const list = document.querySelector("ul");
const items = list.querySelectorAll("li");

Next, we sort all the items by their text content value with:

const sortedList = [...items].sort((a, b) => {
  const c = a.textContent,
    d = b.textContent;
  return c < d ? -1 : c > d ? 1 : 0;
});

Then we add the sorted items into the fragment with:

for (const item of sortedList) {
  frag.appendChild(item);
}

Finally, we append the fragment into the list with:

list.appendChild(frag);

Conclusion

To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions.