使用D3选中时获取复选框的ID

时间:2019-06-08 21:55:33

标签: javascript html d3.js

我有以下格式的Bootstrap表

 <div class="col-sm-8"> 
    <div class="tablecontainer">
      <table class="table table-bordered">
          <thead>
            <tr>
              <th scope="col">Instances</th>
              <th scope="col">Chains</th>
            </tr>
          </thead>
          <tbody>


           <tr>
              <td><input type='checkbox' id='[0]' class='jmolInline'>1</td>
              <td>4LF8|1|A</td>
            </tr>

            <tr>
              <td><input type='checkbox' id='[1]' class='jmolInline'>2</td>
              <td>4LF7|1|A</td>
            </tr>

            <tr>
              <td><input type='checkbox' id='[2]' class='jmolInline'>1</td>
              <td>4B3W|1|A</td>
            </tr>

            <tr>
              <td><input type='checkbox' id='[3]' class='jmolInline'>2</td>
              <td>4AA4|1|A</td>
            </tr>


          </tbody>
      </table>
    </div>

我想获取使用d3检查的复选框的ID。我已经尝试了以下方法,但是它似乎不起作用。使用d3获取存储在数组中的已检查ID的最佳方法是什么?

  var checked = []
  var boxes = d3.selectAll("input.jmolInline:checked");
  boxes.each(function() {
    checked.push(this.id)
  });
  console.log(checked)

1 个答案:

答案 0 :(得分:0)

使用此代码完成工作

var inputs = d3.selectAll('input[type="checkbox"]')._groups[0];
        document.getElementById('submit').addEventListener('click', function() {
            var checked = [];
            for (i = 0; i < inputs.length; i++) {
                if (inputs[i].checked) {
                    checked.push(inputs[i].id);
                }
            }
            document.getElementById('result').innerHTML = 'Array of ids selected ' + checked;
            console.log(checked);
            
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="col-sm-8">
    <div class="tablecontainer">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">Instances</th>
                    <th scope="col">Chains</th>
                </tr>
            </thead>
            <tbody>


                <tr>
                    <td><input type='checkbox' id='[0]' class='jmolInline'>1</td>
                    <td>4LF8|1|A</td>
                </tr>

                <tr>
                    <td><input type='checkbox' id='[1]' class='jmolInline'>2</td>
                    <td>4LF7|1|A</td>
                </tr>

                <tr>
                    <td><input type='checkbox' id='[2]' class='jmolInline'>1</td>
                    <td>4B3W|1|A</td>
                </tr>

                <tr>
                    <td><input type='checkbox' id='[3]' class='jmolInline'>2</td>
                    <td>4AA4|1|A</td>
                </tr>


            </tbody>
        </table>
        <button id="submit">get Id</button>
        <div id="result"></div>
    </div>