Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving value of checkbox in React.js

I want to retrieve the value of my checkbox when it is checked.

I am using this "http://react-component.github.io/checkbox/".

My code looks like this.

<div className="user_box">
    { check.map((values , i)=> {
        return <Checkbox
            name = "checkbox"
            onChange={this.checkvalue.bind(this)}
            value={values.username} 
        />
    })}
</div>

My function:

checkvalue(e){
    // var all_users = [];
    // var value = this.checkbox.value;
    // all_users.push(value);
    // console.log(all_users);

    console.log('checkbox checked:', (e.target.checked));
}

I'm not understanding how to retrieve the value of the checkbox.

like image 482
Manpreet Oberoi Avatar asked Sep 01 '16 09:09

Manpreet Oberoi


People also ask

What is checkbox return value?

Return Value: It returns a string value that represents the value of the value attribute of a input checkbox field.

How do I get checked and unchecked checkbox value in React?

To uncheck a checkbox programmatically in React, we can set the checked prop of the checkbox to a state. We have the checked state that we used to set the checked prop of the checkbox. Then we add a button that calls setChecked to toggle the checked value when we click the button.

Can checkbox have a value?

Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.


2 Answers

Use the Synthetic event parameter, here is an example:

const element1 = "boy";
const element2 = "girl";

<input
 type="checkbox"
 name={element1}
 value={element1}
 onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
 </label>

<input
 type="checkbox"
 name={element2}
 value={element2}
 onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
 </label>




handleChange = (e) => {
// to find out if it's checked or not; returns true or false
const checked = e.target.checked;

// to get the checked value
const checkedValue = e.target.value;

// to get the checked name
const checkedName = e.target.name;

//then you can do with the value all you want to do with it.
};
like image 39
Anayo Oleru Avatar answered Oct 13 '22 23:10

Anayo Oleru


you need to pass the "e, Synthetic event parameter to your handler" :

handleChange(e) {
  let isChecked = e.target.checked;
  // do whatever you want with isChecked value
}

render() {
  // ... your code here
  return (
    {/* your other jsx here */}
    <Checkbox otherProps onChange={e => this.handleChange(e)} />
    {/* your other jsx here */}
  );
}
like image 116
erdysson Avatar answered Oct 14 '22 00:10

erdysson