How to change the checkbox selection and get the updated id's of checkbox items in form submit in React Component?

Viewed 221

I need help in my react code. I am displaying the list of checkbox items using api. My JSON file contains the data which is having IsAssigned True/False. If isAssigned is true for that item, item checkbox will be pre-checked on page load.

Now, I want to change the selection of Checkboxlist items. How can I get the id's of selected Checkboxes and call post/put api calls to make changes in the database.

There are checkboxes that are pre-selected isAssigned=true, unselect the pre-selected checkboxes isAssigned= false, select the checkboxes that are not pre-selected earlier.

Please find my react code and json data below. Also, help me out on achieving the above,

import React from "react";

export class SetDescItems extends React.Component {

       static displayName = Assign_TemplateDescriptions.name;

 

       constructor(props) {

             super(props);

             this.state = {

                    ProdDescrlist: [],

                    checkedItems: new Map(),

             }

 

                    this.handleChange = this.handleChange.bind(this);

                    this.handleSubmit = this.handleSubmit.bind(this);

       }

 

       handleChange(event) {

             var isChecked = event.target.checked;

             var item = event.target.value;

             var id = event.target.id;

             this.setState(prevState => ({ checkedItems: prevState.checkedItems.set(id, item, isChecked) }));

       }

 

      handleSubmit(event) {
             event.preventDefault();
             //Create an Array.
             var checkedItems = new Array();

         //Reference all the CheckBoxes

             var chks = document.getElementsByTagName("INPUT");
          // Loop and push the checked CheckBox id's in Array.

             for (var i = 0; i < chks.length; i++) {

                    if (chks[i].checked) {
                           checkedItems.push(chks[i].id);
               }
            }

      //Display the selected CheckBox id's.

             if (checkedItems.length > 0) {

                    checkedItems = checkedItems.join(",");

                    console.log("Selected ids: " + checkedItems);

             }

             const data = checkedItems;
             //write post api here
             

       }

 

       componentDidMount() {

                    this.getProdDescriptions();

       }

 

       async getProdDescriptions () {

             const url = “/api/getDescriptions”;

             await fetch(url)

                    .then(response => response.json())

                    .then((data) => {

                           this.setState({

                                 ProdDescrlist: data,

                                 loading: false

                           })

                           console.log(this.state.ProdDescrlist)

                    })

       }

       render() {

             return (

                    <div>

                           <form onSubmit={this.handleSubmit} >

                                

                                                      <ul style={{ listStyle: 'none' }}>

                                                            {

                                                                   (this.state.ProdDescrlist.map((item, index) => {

                                                                          return (

 

                                                                                <li key={index}>

                                                                                      <input type="checkbox"

                                                                                             id={item.ProdDescription_ID}

                                                                                             defaultChecked={item.isAssigned == "TRUE"?true:false}

                                                                                             value={item.DescriptionTextPlain}

                                                                                             onChange={this.handleChange} />

                                                                                     

                                                                                             &nbsp;{item.DescriptionTextPlain}

                                                                                     

                                                                                </li>

                                                                         )

                                                                   }

                                                                   ))

                                                            }

                                                            </ul>

                                                      <button type="submit">Submit</button>

                                                                                            

                           </form>

                    </div>

 

             );

       }

}

 

export default SetDescItems;

[{"ProdDescription_ID":2863,"isAssigned":"TRUE","DisplaySequence":0,"DescriptionTextPlain":"A1Testig"},

{"ProdDescription_ID":2865,"isAssigned":"TRUE","DisplaySequence":0,"DescriptionTextPlain":"test"},

{"ProdDescription_ID":1778,"isAssigned":"FALSE","DisplaySequence":0,"DescriptionTextPlain":"Testing4"},

{"ProdDescription_ID":2864,"isAssigned":"FALSE","DisplaySequence":0,"DescriptionTextPlain":"A2 "},

{"ProdDescription_ID":1544,"isAssigned":"FALSE","DisplaySequence":5,"DescriptionTextPlain":"ProductGuide"},

{"ProdDescription_ID":1535,"isAssigned":"TRUE","DisplaySequence":10,"DescriptionTextPlain":"testexample"},

{"ProdDescription_ID":1536,"isAssigned":"FALSE","DisplaySequence":15,"DescriptionTextPlain":"Note"}]

1 Answers

You need to use checked prop in input tag

import "./styles.css";

import React from "react";

export class SetDescItems extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ProdDescrlist: [],
      checkedItems: []
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const id = parseInt(event.target.id, 10);
    const index = this.state.checkedItems.indexOf(id);
    const updatedArray = [...this.state.checkedItems];
    if (index !== -1) {
      updatedArray.splice(index, 1);
    } else {
      updatedArray.push(id);
    }
    this.setState((prevState) => ({
      checkedItems: updatedArray
    }));
  }

  handleSubmit(event) {
    event.preventDefault();
    let value = "";

    this.state.checkedItems.forEach((item) => {
      if (item) {
        value = value === "" ? item : value + "," + item;
      }
    });

    if (value !== "") {
      alert(value);
    }
  }

  componentDidMount() {
    this.getProdDescriptions();
  }

  async getProdDescriptions() {
    const url = "/api/getDescriptions";
    await fetch(url)
      .then((response) => response.json())
      .then((data) => {
        let items = data.reduce((acc, item) => {
          if(item.isAssigned === "TRUE") acc.push(item.ProdDescription_ID);
          return acc;
        }, []);
        this.setState({
          ProdDescrlist: data,
          loading: false,
          checkedItems: items
        });
      });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <ul style={{ listStyle: "none" }}>
            {this.state.ProdDescrlist.map((item, index) => {
              return (
                <li key={index}>
                  <input
                    type="checkbox"
                    id={item.ProdDescription_ID}
                    defaultChecked={item.isAssigned === "TRUE" ? true : false}
                    value={item.DescriptionTextPlain}
                    onChange={this.handleChange}
                  />
                  &nbsp;{item.DescriptionTextPlain}
                </li>
              );
            })}
          </ul>

          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

Related