简体   繁体   中英

check box checked value not passing

I have an input checkbox, whose value is always logging on the console as false even when the box itself is checked. Am I forgetting to do something, am I not passing something needed? I am fairly new to React and js. My apologies for not putting in all the code for some reason stackOverflow wont let me paste all of it

Thank you for your help.


class Orders extends Component {
  componentDidMount() {
    this.props.fetchOrders();
  }

  complete = () => {
    const completed = document.getElementById("complete").checked;
    // console.log("this is complete", completed);
    if (completed.checked === true) {
      // text.style.display = "block";
      console.log("im am checked");
    } else {
      console.log("im am NOT checked");
      //text.style.display = "none";
    }
  };

<input>
                <td>
                  <input
                    type="checkbox"
                    name="complete"
                    id="complete"
                    onChange={() => this.complete()}
                  ></input>
                </td>
            

You should avoid using a selector like this with React, this misses the point of the library. It's probably a problem that appeared when you copied the code but the html elements should be returned with the render() function. Instead you should pass the event to your callback function and use the event passed by the dom element like this:

class Orders extends Component {
  componentDidMount() {
    this.props.fetchOrders();
  }

  complete = (e) => {
    if (e.target.checked) {
      console.log("im am checked");
    } else {
      console.log("im am NOT checked");
    }
  };

Check for the checked property in the target element. This should work.

  const complete = (e) => {
    if (e.target.checked) {
      console.log("im am checked");
    } else {
      console.log("im am NOT checked");
    }
  };
  return (
    <div>
      <input
        type="checkbox"
        name="complete"
        id="complete"
        onChange={(e) => complete(e)}
      />
    </div>
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM