Use React to get the selected value of a checkbox
P粉590929392
P粉590929392 2023-09-02 22:36:49
0
2
541

I'm trying to retrieve the checked value of a checkbox and save it into an array. I tried:

arr.push(setNewItem(checked)) arr.push(e.target.value.checked) arr.push(items.checked)

But these return values of the wrong type or undefined.

const [checkedItems, setCheckedItems] = useState([]); const handleChange = (e) => { if (e.target.checked) { var arr = [...checkedItems]; //arr.push(setNewItem(e.target.value.checked)); setCheckedItems(arr); console.log(arr); } else { checkedItems = ""; } setIsChecked((current) => !current); };
return ( 
setNewItem(e.target.value)} onKeyPress={handleOnKeyPress} /> addItem()}>Add {items.map((item) => { return ( {item.value} {""} deleteItem(item.id)}> X ); })}
);
P粉590929392
P粉590929392

reply all (2)
P粉575055974

This may solve your problem.

const [checkedItems, setCheckedItems] = useState([]); const handleChange = (e) => { setCheckedItems( prev => [...prev, e.target.checked]); setIsChecked((current) => !current); };
    P粉846294303
    arr.push(e.target.checked);

    is the correct way to get rid of:

    else { checkedItems = ""; }

    You cannot update status this way, and when you try to uncheck an input, an error will appear:

    Now let's see what you want to do, every time an input is checked, you storee.target.checked, socheckedItemswill look like this:

    [true, true, true, true, true, true, true, true]

    Why do you need this? A better approach is to store the id of the selected item:

    const handleChange = (isChecked, id) => { var arr = [...checkedItems]; if (isChecked) { arr.push(id); setCheckedItems(arr); } else { setCheckedItems(checkedItems.filter((storedId) => storedId !== id)); // 如果对应的输入未选中,则从checkedItems中删除id } };

    Then in jsx:

     { handleChange(e.target.checked, item.id); }} />;

    Now look at this:

    You are mapping viaitems, creating multiple checkboxes, but they all share the same value. The value attribute of the checkbox is not what you think, please learn more inhere. So you can usevalue={item.id}to set a unique value for each input, and get rid of the useState hook ofisChecked, which you don't really need.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!