Janio Carvalho
Janio Carvalho

Reputation: 117

How to return true or false using the input checkbox in react js?

My input checkbox always returns true, when i mark it passsa true correctly, but when i unmark tb i get true. I would like the checkbox to return true when checked and false when unchecked, this way I would apply my logic in the handlesubmit function.


    handleChange = e => {
        const { name, value } = e.target;
        console.log(name, value);
        switch (name) {

          case 'period': this.json.schedule = 'period'; break;

    }


 <input
       type="checkbox"
       name="period"
       defaultValue
       onChange={this.handleChange}
 />

Upvotes: 1

Views: 25044

Answers (4)

Adem
Adem

Reputation: 61

You can use useState.

import React, { useState } from 'react';

const App = () => {
    const [Check, setCheck] = useState(false);
    return (
        <div>
            <h1>{Check ? 'Checked' : 'Not checked'}</h1>
            <input type="checkbox" onChange={(e) => setCheck(e.target.checked) }/>
        </div>
    );
};

export default App;

Upvotes: 2

Neil
Neil

Reputation: 2058

Checkout the value of e.target.checked.

In your case, change this line: const { name, value } = e.target to include checked.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: true
    }
  }
  
  handleChange = (e) => {
    const { checked } = e.target
    this.setState({
      checked: checked
    })
  }
  
  render() {
    return (
      <div>
        <input type="checkbox"
               onChange={e => this.handleChange(e)}
               defaultChecked={this.state.checked}/>
        {this.state.checked.toString()}
      </div>
    )
  }
}

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

<div id="testing"></div>

Upvotes: 10

NFDev
NFDev

Reputation: 68

You aren't checking wether the box is checked or not, try:

handleChange = e => {
    if (document.getElementByClassName("period").checked) {
        // box is checked
    } else {
        // box is unchecked
    }
}

Upvotes: 0

Larson Carter
Larson Carter

Reputation: 163

You first need to define what check is considered? If it is check it is true and when it is not checked it is false. Here is some code to get you started.

{   this.state.data.map(function(item, index) { return (
    <input type="checkbox" checked={item.value} onChange={this.handleChange.bind(this, index)}/>
  );
      }.bind(this))
}

Upvotes: 0

Related Questions