简体   繁体   中英

How to limit the number of selected check-boxes in React JS?

I want to limit the maximum number of checked check-boxes to be 3. At the same time I also want to create an array of the selected values. Please note that, I am using Ant design's checkbox . Code is as given in codesandbox.io .

handleCheckbox = (e) => {
    let qlen = document.querySelectorAll('input[type="checkbox"]:checked').length;
    if(qlen < 3) {
    if(e.target.checked) {
      this.setState({
        indstryValue: this.state.indstryValue.concat([e.target.value])
      });
    } else {
      var arr = this.state.indstryValue;
      arr = arr.filter(item => item !== e.target.value);
      this.setState({
        indstryValue: arr
      });
    }
  }

  var checks = document.querySelectorAll('input[type="checkbox"]');
  var max = 2;
  for (var i = 0; i < checks.length; i++)
    checks[i].onclick = selectiveCheck;
  function selectiveCheck(event) {
    console.log(event.target);
    var checkedChecks = document.querySelectorAll('input[type="checkbox"]:checked');
    if (checkedChecks.length >= max + 1)
      return false;
  }
}

You can make use of react state to do this. The following example conditionally disables checkboxes when two are checked. Codesandbox

import React from "react";
import ReactDOM from "react-dom";
import { Checkbox, Row, Col } from "antd";

class CheckBoxed extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: []
    };
  }
  onChange = checkedValues => {
    this.setState(() => {
      return { checked: checkedValues };
    });
  };

  isDisabled = id => {
    return (
      this.state.checked.length > 1 && this.state.checked.indexOf(id) === -1
    );
  };
  render() {
    return (
      <Checkbox.Group style={{ width: "100%" }} onChange={this.onChange}>
        <Row>
          <Col span={8}>
            <Checkbox value="A" disabled={this.isDisabled("A")}>
              A
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="B" disabled={this.isDisabled("B")}>
              B
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="C" disabled={this.isDisabled("C")}>
              C
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="D" disabled={this.isDisabled("D")}>
              D
            </Checkbox>
          </Col>
          <Col span={8}>
            <Checkbox value="E" disabled={this.isDisabled("E")}>
              E
            </Checkbox>
          </Col>
        </Row>
      </Checkbox.Group>
    );
  }
}

ReactDOM.render(<CheckBoxed />, document.getElementById("container"));

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