D3选择多个​​标签提取值

时间:2019-02-22 17:31:14

标签: javascript html d3.js

我有一个选择标签。我想将选择的值提取到数组中,但是我似乎只能提取第一个值。

请在下面找到我要实现的目标的简化版本。

我使用以下方法尝试了几种不同的选择:

  • this.value
  • node().value

但这似乎只是提取第一个选定的值。

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <script src="https://d3js.org/d3.v5.min.js"></script>    
  </head>

  <body>
    <!-- Build the select boxes -->
    <p>Single select tag</p>
    <select  class="form-control" id = "select_single" >
      <option value="a">a</option>
      <option value="b">b</option>
      <option value="c">c</option>
      <option value="d">d</option>            
    </select>   
    <p id = "select_single_p"> </p>
    <br>
    <br>
    <p>Multiple select tag</p>    
    <select multiple class="form-control" id = "select_multiple" >
      <option value="a">a</option>
      <option value="b">b</option>
      <option value="c">c</option>
      <option value="d">d</option>            
    </select>   

    
  </body>   
  <script>
  // This works for a single select 
  d3.select("#select_single")
  .on("change",function(d){
    console.log("this is the select single value " + this.value)
  })
  // But for multiple selects I can only extract the first value
 d3.select("#select_multiple")
  .on("change",function(d){this.value.len;
    console.log("this is the select multiple value " + this.value )

    console.log(d3.select('#select_multiple').node().value) 

  })  


  </script>

</html>

1 个答案:

答案 0 :(得分:2)

您可以采取一些方法,对于初学者来说,您可以在change函数中使用纯正的javascript:

d3.select("#select_multiple")
 .on("change",function(d){
   var values = Array.from(this.options) // create an array from the htmlCollection
     .filter(function(option) { return option.selected })  // filter for selected values
     .map(function(option) { return option.value; }); // return a new array with the selected values
  console.log(values);
})

另一种选择是使用d3选择所选的选项,并为每个选项获取值:

d3.select("#select_multiple")
 .on("change",function(d){ 
    var values = [];
    selected = d3.select(this) // select the select
      .selectAll("option:checked")  // select the selected values
      .each(function() { values.push(this.value) }); // for each of those, get its value
    console.log(values)
})