mardi 18 janvier 2022

Disable checkbox for item that is not defaultChecked

I have two checkbox items. One of them will be default selected upon entry into the page, by props. Depending on which item is selected on default, the other checkbox item should be disabled upon entry into the page.

Also, the user can deselect the default checked item, in which case, both checkboxes become enabled for selection. When the user then selects one of the two options, the non-selected option will become disabled again.

What works: When I deselect the default option and reselect one of the two checkboxes, the disabled behavior works correctly (in that the non-selected option becomes disabled).

What does not work and need to find a fix for: When I enter the page, the option that is NOT selected by default needs to be disabled. I need to figure out how to disable the non-selected option upon entry into the page.

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;

         // NOTE: 'checked' is a boolean

         if(value=="a") {
            this.setState( {aSelected: checked} );
         }

         if(value=="b") {
            this.setState( {bSelected: checked} );
         } 
     }

     // returns default value of each checkbox based on props
     handleDefault = (trueOrFalse, name) => {   
         if(name == "a") { return trueOrFalse; } 
         if(name == "b") { return trueOrFalse; }
     }

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}
   defaultChecked={this.handleDefault(this.props.selected["a"], "a")}
</input>

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



Aucun commentaire:

Enregistrer un commentaire