Unable to bind the Radio button and checkbox data on button click in react hooks

前端 未结 1 1713
后悔当初
后悔当初 2021-01-26 07:49

I am having a form, When I submit the data it is going to server and I displayed the data in a table.. In the Table I am having edit button, When clicked on Edit button, the dat

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 07:56

    Change state to

    const [data, setdata] = useState({
      UserName: "",
      dropDown: "",
      gender: null,
      checking: []
    });
    

    Update the handler to access the radio and checkbox id attributes

    const handleChange = (e) => {
      if (e.target.name !== "gender" && e.target.name !== "checking") {
        setdata({ ...data, [e.target.name]: e.target.value });
      } else if (e.target.name === "gender") {
        let allgenders = document.getElementsByName("gender");
        allgenders.forEach((allradio) => {
          if (allradio.checked) {
            setdata({ ...data, [e.target.name]: e.target.id }); // <-- grab input id
          }
        });
      } else if (e.target.name === "checking") {
        let getallCheckboxes = [];
        let allCheckboxes = document.getElementsByName("checking");
        allCheckboxes.forEach((allchecks) => {
          if (allchecks.checked) {
            getallCheckboxes.push(allchecks.id); // <-- grab checkbox id
          }
        });
        setdata({ ...data, [e.target.name]: getallCheckboxes });
      }
    };
    

    Update/add handleClear to reset the state

    handleClear = () => {
      setdata({
        UserName: "",
        dropDown: "",
        gender: null,
        checking: []
      });
    };
    

    Add id properties and change the value prop to checked and pass a boolean value

    
    
      
    
    
      
    
    
    ...
    
    
    



    0 讨论(0)
提交回复
热议问题