33

is there any way to get value of checkbox using ref in React. Normal way return always value "on" to me.

var MyForm = React.createClass({
    save: function(){
        console.log(this.refs.check_me.value);
    },

    render: function(){
        return <div><h1>MyForm</h1>
            <div className="checkbox">
                <label>
                    <input type="checkbox" ref="check_me" /> Check me out
                </label>
            </div>
            <button className="btn btn-default" onClick={this.save}>Submit</button>
        </div>
    }
});
0

4 Answers 4

56

For checkbox, use "checked" instead of "value":

var MyForm = React.createClass({
  save: function () {
    console.log(this.refs.check_me.checked);
  },

  render: function () {
    return <div><h1>MyForm</h1>
      <div className="checkbox">
        <label>
          <input type="checkbox" ref="check_me" /> Check me out
        </label>
      </div>
      <button className="btn btn-default" onClick={this.save}>Submit</button>
    </div>
  }
});

As a result:

enter image description here

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

3 Comments

Returns always undefined :-(
That's strange it works for me. I added a picture in my post if it can help
I'm very sorry @Damien Leroux I made a mistake when I copy your source code. Your code is valid. Thanks a lot. I works!
16

There is a classic way to catch the event and corresponding values with the help of:

event.target.checked, event.target.name

You can see an example:

class MyForm extends React.Component {
    onChangeFavorite(event){
        console.log(event.target.checked, event.target.name);
    };
    render(){
        return (<div><h1>MyForm</h1>
            <div className="checkbox">
                <label>
                   <input type="checkbox" name="myCheckBox1" 
                     onChange={this.onChangeFavorite} 
                     defaultChecked={false} /> 
                   Check me out
                </label>
            </div>
            <button className="btn btn-default" onClick={this.save}>Submit</button>
        </div>)
    };
};

Comments

11

You can make the checkbox a controlled element by listening to onChange and giving it a state value. Try the following:

var MyForm = React.createClass({
  save: function(){
    console.log(this.refs.check_me.value);
  },

  toggleCheckboxValue: () => {
    this.setState({checkBoxValue: !this.state.checkboxValue});
  },

  render: function(){
    return <div><h1>MyForm</h1>
        <div className="checkbox">
            <label>
                <input type="checkbox" ref="check_me" value={this.state.checkboxValue} onChange={this.toggleCheckboxValue} /> Check me out
            </label>
        </div>
        <button className="btn btn-default" onClick={this.save}>Submit</button>
    </div>
  }
});

whenever the checkbox is clicked it will run the toggleCheckboxValue function, which will toggle the value of this.state.checkboxValue.

Just don't forget to initialize the this.state.checkboxValue function in your code.

Note: As ivarni pointed out, you may want to control the checked value specifically for checkboxes rather than value. Though both solutions will work.

6 Comments

Not sure why this was downvoted. It's a perfectly valid, functional implementation of a controlled input element.
I don't know. The answer is fine.
I'm not going to downvote as the answer does provide a solution, but I personally feel it's abusing what value should be used for. If you look at mdn you'll see that it says The value attribute is used to define the value submitted by the checkbox. The checked attribute is used to indicate whether this item is selected. I haven't tested how it would affect a screenreader but it wouldn't surprise me if this confuses some poor blind person down the road.
@ivarni, well it's up to the programmer to give value an appropriate value instead of something that isn't. It's still perfectly valid to have a controlled checkbox.
I'm just saying that personally I would control the checked attribute and not the value for reasons I already outlined.
|
0

I'm not sure why you want it using ref specifically, but it can be done nativily:

import React from 'react';

function CheckBox() {
  const [isSave, setIsSave] = React.useState(false);
  const handler = (value) => {
    console.log(value);
    setIsSave(value);
  };

  return (
    <div>
      <input type="checkbox" onChange={(ev) => handler(ev.target.checked)} />
      <label> Save me..</label>
    </div>
  );
}

export default CheckBox;

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.