hous1956
hous1956

Reputation: 33

How do i select all checkboxes in Javascript?

I am a beginner with javscript So i will be thankful for explanation.

 {isolate_list.map((row) => {
                        return (
                          <FormControlLabel
                            control={
                              <Checkbox
                                color="primary"
                                checked={!!checked}
                                onChange={toggleCheckbox}
                                name="checkedA"
                              >
                                {" "}
                              </Checkbox>
                            }
                            label={row.isolatename}
                          >
                            {""}
                          </FormControlLabel>
                        );
                      })}

and i have this button

                    <Button
                      onClick={selectall}
                      style={{ margin: 50 }}
                      variant="outlined"
                      label="SELECT ALL ISOLATES"
                    >
                      SELECT ALL ISOLATES
                    </Button>

Can anyone help how can i use the button to select all checkboxes and in the same time i can select every checkbox alone by clicking on it? I beginn with this part but i am not sure

 const [checked, setChecked] = React.useState(true);
  const toggleCheckbox = (event) => {
    setChecked(event.target.checked);
  };

Upvotes: 3

Views: 914

Answers (3)

gustavoilhamorais
gustavoilhamorais

Reputation: 152

You may remember that it is React JS and not only JS that we are talking about.

In React you want to control data in the way of a state. There are a lot of ways to do so with check boxes, I'm contributing with one that you can see in the code snippet below:

import React, {useState} from "react";

export default function CheckBoxesControllers() {
  const [checkboxes, setCheckboxes] = useState(() => [
    { id: "0", checked: false },
    { id: "1", checked: false },
    { id: "2", checked: false },
  ]);

  const handleUpdate = (event) => {
    const { target: {id, checked} } = event;
    setCheckboxes(currentState => {
      const notToBeUpdated = currentState.filter(input => input.id !== id);
      return [
          ...notToBeUpdated,
        { id, checked }
      ]
    });
  }

  function toggleSelectAll() {
    setCheckboxes(currentState => currentState.map(checkbox => ({...checkbox, checked: !checkbox.checked})));
  }

  return (
      <>
          {checkboxes?.length ? (
              checkboxes.map((checkbox, index) => {
                return (
                    <input
                      checked={checkbox.checked}
                      id={checkbox.id}
                      key={index}
                      type="checkbox"
                      onChange={event => handleUpdate(event)}
                    />
                );
              })
          ) : <></>}
          <button onClick={toggleSelectAll}>Toggle Select All</button>
      </>
  )
}

This code is meant to serve you as an example of how to work properly with react state in the hook way, but there are other way, as you can see in the Documentation

Upvotes: 0

wentris
wentris

Reputation: 503

The simplest implementations(without any form manager):

  1. Declare state to store our checked ids array.

const [checkedIds, setCheckedIds] = useState([]);

  1. implement handler.
const handleCheck = useCallback((id) => {
  return () => {
    setCheckedIds(prevIds => prevIds.includes(id) ? prevIds.filter(item => item !== id) : [...prevIds, id]);
  };
}, []);

  1. render our checkboxes and apply handler.
list.map(({ id, isolatename }) => (
  <FormControlLabel
    key={id}
    control={
      <Checkbox
        color="primary"
        checked={checkedIds.includes(id)}
        onChange={handleCheck(id)}
        name={`checkbox_${id}`}
      />
    }
    label={isolatename}
  />)
))

ps. in case if <Checkbox/> props 'onChange' returns callback like this (isChecked: boolean) => {} we can simplify (2) step.

const handleCheck = useCallback(id => {
  return isChecked => {
    setCheckedIds(prevIds => isChecked ? prevIds.filter(item => item == id) : [...prevIds, id]);
  };
}, []);

Upvotes: 1

aligumustosun
aligumustosun

Reputation: 152

You should hold checkbox value's in the and give the state value as a property to each. For example

<Checkbox 
  color="primary" 
  onChange={toggleCheckbox}
  name="checkedA"
  value={checked}
>

And then in the onClick function

setChecked();

Upvotes: 1

Related Questions