25

I'm trying to change the value of the checkbox with the onChange function of another input field.

I have something like this:

class price extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            minValue: 0,
            maxValue: 20000,
            step: 1000,
            firstValue: null,
            secondValue: null,
            chcboxValue: false
        };

        this.handleChange = this.handleChange.bind(this);
    }

    componentWillMount() {
        this.setState({firstValue: this.state.minValue, secondValue: this.state.maxValue});
    }

    handleChange(name, event) {
        let value = event.target.value;
        // We set the state value depending on input that is clicked
        if(name === "second") {
            if(parseInt(this.state.firstValue) < parseInt(value)) {
                this.setState({secondValue:value});
            }
        } else {
            // The first value can't be greater than the second value
            if(parseInt(value) < parseInt(this.state.secondValue)) {
                this.setState({firstValue: value});
            }
        }

        // We set the checkbox value
        if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)) {
            this.setState({chcboxValue: true});
        } else {
            this.setState({chcboxValue: false});
        }
    }

    render() {
        const language = this.props.language;
        return (
            <div>
                <div className="priceTitle">{language.price}</div>
                <InputRange language={language}
                            firstValue={parseInt(this.state.firstValue)}
                            secondValue={parseInt(this.state.secondValue)}
                            minValue={parseInt(this.state.minValue)}
                            maxValue={parseInt(this.state.maxValue)}
                            step={parseInt(this.state.step)}
                            handleChange={this.handleChange}
                            chcboxValue={this.state.chcboxValue}/>
            </div>
        );
    }
}

My InputRange component is something like this:

const inputRange = ({language, firstValue, secondValue, minValue, maxValue, step, handleChange, chcboxValue}) => {
    return (
        <div>
            <div className="rangeValues">Range : {firstValue} - {secondValue}</div>
            <section className="range-slider">
                <input type="checkbox" checked={chcboxValue} />
                <input type="range" value={firstValue} min={minValue} max={maxValue} step={step}  onChange={handleChange.bind(this, "first")} />
                <input type="range" value={secondValue} min={minValue} max={maxValue} step={step} onChange={handleChange.bind(this, "second")} />
                <div className="minValue">{minValue}</div>
                <div className="maxValue">{maxValue}</div>
            </section>
        </div>
    );
};

The checkbox value on initial load is set to false. When the user changes the value of the price range slider, I want that the checkbox value to change to true.

When the user changes the value of the price range slider to their initial values (min and max values), I want the checkbox value to again change to false.

It isn't working in my example.

Any ideas?

4
  • you sure it is an OR ? (||) you say When user changes the values of the price range slider to their initial values (min and max values) Commented Aug 30, 2016 at 9:55
  • If one of those values is not equal to min and max value, it means that user has changed the price slider, right? Commented Aug 30, 2016 at 9:57
  • If ONE is NOT equal (so say you change A but not B A == initial value|| B == initial value would evaluate to TRUE, NOT changin A or B would result in the same, and only changing both would return TRUE, therefore as you correctly say if ONE of them is not the initial one you don't want it to return TRUE, therefore it is an AND operator). Besides I don't know if there are more errors in your code, but changing the || for && is a good start. :) Commented Aug 30, 2016 at 10:06
  • 1
    I want to return true if one of them is not the initial one. If min value == 0 and max value == 20000, and if Ais changed from 0 to 1000 and B is the same, thus 20000; then I want to change checkbox to true. Commented Aug 30, 2016 at 10:10

6 Answers 6

13

not sure but try it :

React.createElement('input',{type: 'checkbox', defaultChecked: false});

or

<input type="checkbox" checked={this.state.chkbox} onChange={this.handleChangeChk} />

or

var Checkbox = React.createClass({
  getInitialState: function() {
    return {
      isChecked: true
    };
  },
  toggleChange: function() {
    this.setState({
      isChecked: !this.state.isChecked // flip boolean value
    }, function() {
      console.log(this.state);
    }.bind(this));
  },
  render: function() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.toggleChange} />
        Check Me!
      </label>
    );
  }
});

React.render(<Checkbox />, document.getElementById('checkbox'));
Sign up to request clarification or add additional context in comments.

Comments

11

we can set an onChange prop on the input field and handle the event.

App.js

import {useState} from 'react';

export default function App() {
  const [isChecked, setIsChecked] = useState(false);

  const handleChange = event => {
    setIsChecked(event.target.checked);

    // 👇️ this is the checkbox itself
    console.log(event.target);

    // 👇️ this is the checked value of the field
    console.log(event.target.checked);
  };

  return (
    <div>
      <input
        type="checkbox"
        id="checkbox-id"
        name="checkbox-name"
        onChange={handleChange}
        checked={isChecked}
      />
    </div>
  );
}


Comments

6

Your example is not working properly because you are checking the value before this.setState() is completed. Don't forget that this.setState() does not immediately mutate the state.

To fix it, you can create a function where you update the value of the checkbox

updateCheckBox(){
   if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)){
        this.setState({chcboxValue: true});
    }else{
        this.setState({chcboxValue: false});
    }
}

and then pass it to your handleChange this.setState() calls.

handleChange(name, event){
    let value = event.target.value;
    //We set the state value depending on input that is clicked
    if(name === "second"){
        if(parseInt(this.state.firstValue) < parseInt(value)){
            this.setState({secondValue:value}, this.updateCheckBox);
        }
    }else{
        //The first value can't be greater than the second value
        if(parseInt(value) < parseInt(this.state.secondValue)) {
            this.setState({firstValue: value}, this.updateCheckBox);
        }
  }

jsfiddle

Comments

2

This is kind of old but in case it helps.

I started relying on this syntax

Declare in the class, a variable to store the state:

const [agreeToAllTerms, setAgreeToAllTerms] = useState(false);

Declare the checkbox

<Checkbox checked={agreeToAllTerms} onChange={(event)=> {handleChangeChk(event)}}/> 

And then in the function checked the current state of the checkbox like this.

const handleChangeChk = (chkValue) => {
    setAgreeToAllTerms(chkValue.target.checked);
}

Comments

1

Here is a generic form change handler that also supports checkboxes

 onFormChange: (e) => {
    // In my example all form values are stored in a state property 'model'
    let model = this.state.model;

    if(e.target.type == 'checkbox') {

      if(model[e.target.name] === false) {
        model[e.target.name] = true;
      } else if(model[e.target.name] === true) {
        model[e.target.name] = false;
      } else {
        // if the property has not be defined yet it should be true
        model[e.target.name] = true;
      }
    } else {
      model[e.target.name] = e.target.value;
    }

    // Update the state
    this.setState({
      model: model
    });
  }

Comments

1

you shoud know how we can bind html input value in react. here this example for beginer. easy to understand

const chk= true

chkchk() ={ console.log("checkbox event fire")}
<input name="abc"
 type="checkbox"  checked={chk.toString()}        
 onChange={chkchk} 
            /> 

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.