20

I am messing with checkboxes and I want to know that is there a way in which I can uncheck a checkbox on click of a button by calling a function?? If so? How can I do that?

<input type="checkbox" className="checkbox"/>
<button onClick={()=>this.unCheck()}

How can I uncheck the checkbox programmatically and what if I have multiple checkboxes generated dynamically using map function. How can I uncheck them If I want to?

4
  • $('.checkbox').prop('checked', false); Commented Apr 25, 2017 at 5:58
  • @SureshPonnukalai I am not using jquery anywhere.. How can I do it without jquery? Commented Apr 25, 2017 at 6:00
  • use plain javascript: document.getElementsByClassName("checkbox"). You will get array of object, then assign each one with checked=false Commented Apr 25, 2017 at 6:02
  • 1
    i have created fiddle and given below for your ref Commented Apr 25, 2017 at 6:09

6 Answers 6

20

There is property of checkbox checked you can use that to toggle the status of check box.

Possible Ways:

1- You can use ref with check boxes, and onClick of button, by using ref you can unCheck the box.

2- You can use controlled element, means store the status of check box inside a state variable and update that when button clicked.

Check this example by using ref, assign a unique ref to each check box then pass the index of that item inside onClick function, use that index to toggle specific checkBox:

class App extends React.Component{

   constructor(){
      super();
      this.state = {value: ''}
   }
   
   unCheck(i){
      let ref = 'ref_' + i;
      this.refs[ref].checked = !this.refs[ref].checked;
   }
   
   render(){
     return (
       <div>
        {[1,2,3,4,5].map((item,i) => {
           return (
              <div>
                 <input type="checkbox" checked={true} ref={'ref_' + i}/>
                 <button onClick={()=>this.unCheck(i)}>Toggle</button>
              </div>
            )
        })}      
       </div>
     )
   }

}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Check this example of controlled element, means storing the state of checkbox inside state variable, and on click of button change the value of that:

class App extends React.Component{

   constructor(){
      super();
      this.state = {value: []}
   }
   
   onChange(e, i){
      let value = this.state.value.slice();
      value[i] = e.target.checked;
      this.setState({value})
   }
       
   unCheck(i){
      let value = this.state.value.slice();
      value[i] = !value[i];
      this.setState({value})
   }
       
   render(){
     return (
        <div>
           {[1,2,3,4,5].map((item,i) => {
             return (
                <div>
                  <input checked={this.state.value[i]} type="checkbox" onChange={(e) => this.onChange(e, i)}/>
                  <button onClick={()=>this.unCheck(i)}>Toggle</button>
                </div>
              )
           })}      
         </div>
       )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Sign up to request clarification or add additional context in comments.

4 Comments

Hey mayank. Very nice explaination :) As always you rock ;)
thanks, check the another snippet, how to use controlled checkbox element, let me know if you any other help :)
Hi @MayankShukla, when I tried this.refs.[some_ref_name] it returns a HTMLInputElement instead of an object so I can't set any checked field, do you know how to fix this?
@TriNguyen ref will return the html element only, and then we can change the checked property of element. check/run the first snippet you will get a better idea.
7

React

Checked

  1. Using State
     <input type="radio" name="count" value="minus" onChange={this.handleRadioChange} checked={this.state.operation == "minus"} /> Decrement

2.Using Refs

<input type="radio" name="count" ref="minus" /> Decrement
onSubmit(e){ this.refs.minus.checked = false }

Comments

6

Using plain javascript you can acheive like below.

 function unCheck() {
   var x = document.getElementsByClassName("checkbox");
   for(i=0; i<x.length; i++) {
      x[i].checked = false;
    }   
 }

Small DEMO

Comments

2

I was thinking of a thing like that:

<input onChange={(input) => this.onFilterChange(input)} className="form-check-input" type="checkbox" />

onFilterChange = (input) => { let { value, checked } = input.target;}

unCkeckAll = () => {
    [...document.querySelectorAll('.form-check-input')].map((input) => {
        if (input.checked) {
            let fakeInput = {
                target: {
                    value: input.value,
                    checked: false
                }
            }
            input.checked = !input.checked;
            this.onFilterChange(fakeInput);
        }
        return null;
    })
}

Comments

1

Checkboxes have a checked property, you can hook it to the state and change it dynamically. Check these links:

https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs

http://react.tips/checkboxes-in-react/

Comments

-2

Sometime its good to use plain javascript. If you have of checkbox value in any of your state then try this

 let checkboxValue = xyz
 document.querySelectorAll("input[value="+checkboxValue+"]")[0].checked = false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.