jeudi 13 janvier 2022

Select only ONE or NONE of the checkbox inputs

My goal is to have two checkbox items, where the user can only select ONE or select NONE. While one is selected, the other should be disabled. I have this so far, but it is not working as I expected.

If there is a better way to this overall, please let me know!!

I have a class component with the following content:

  constructor(props) {
     super(props);
     this.state = {
       aSelected: false,
       bSelected: false
     }
  }

 handleCheckboxChange = (e) => {   
     const { checked, value } = e.target;
    
     console.log( 'checked: ', checked );

     if(value=="a") {
        this.setState( {aSelected: checked}, () =>  {
        console.log('aSelected: ', this.state.aSelected);
        console.log("---")
     });
     }

     if(value=="b") {
        this.setState( {bSelected: checked}, () =>  {
        // console.log('bSelected: ', this.state.bSelected);
        // console.log("---")
     });
     } 
 }

Somewhere inside the render return, I have this:

<input>
   type="checkbox"
   value="a"
   onChange={this.handleCheckboxChange}
   disabled={ (this.state.aSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true} 
</input>

<input>
   type="checkbox"
   value="b"
   onChange={this.handleCheckboxChange}
   disabled={ (this.state.bSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true}
</input>

Problems I'm having:

  1. The disabled behavior is NOT matching up with how I detailed it in the first line.
  2. this.state.aSelected and this.state.bSelected always log false no matter how many times I select and unselect the checkbox. The checked value is correctly toggled, though. (Below is the ouput for toggling the "a checkbox"):

enter image description here




Aucun commentaire:

Enregistrer un commentaire