获取多选下拉列表的所有值单击按钮

时间:2017-06-16 08:42:48

标签: jquery

我使用下面的代码行来获取下拉列表的所有值。

$("#assigne option:selected").each(function() {
  var $this = $(this);
  if ($this.length) {
    var selText = $this.text();
    console.log(selText);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row form-inline" style="padding-left:10px">
  <div class="col-md-3">
    <div class="form-group is-filled">
      <h5>Assigned </h5>
      <select id="assigne" multiple="multiple" style="width:200px;">
                                         <option value="gnanadeep.bitra">Gnanadeep</option>
                                         <option value="nimish.vaibhav">Nimish</option>
                                         <option value="srividya.dommeti">Srividya</option>
                                         <option value="shrutika.agrawal">Shrutika</option>
                                         <option value="srinilaya.pemmaraju">Nilaya</option>
                                         <option value="nishath">Nishath</option>
                                         <option value="ravikiran.kothamasu">Ravi Kiran</option>
                                         <option value="swami.sukumaran">Swami</option>
                                      </select>
    </div>
  </div>
</div>

但是我收到了一个错误:

  

未捕获的TypeError:无法读取属性'each'的null

1 个答案:

答案 0 :(得分:0)

以下是您修改后的代码:

&#13;
&#13;
$("#submit").on('click', function() {
  var foo = [];
  $('#assigne :selected').each(function(i, selected) {
    foo[i] = $(selected).text();
  });
  console.log(foo);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row form-inline" style="padding-left:10px">
  <div class="col-md-3">
    <div class="form-group is-filled">
      <h5>Assigned </h5>
      <select id="assigne" multiple="multiple" style="width:200px;">
        <option value="gnanadeep.bitra">Gnanadeep</option>
        <option value="nimish.vaibhav">Nimish</option>
        <option value="srividya.dommeti">Srividya</option>
        <option value="shrutika.agrawal">Shrutika</option>
        <option value="srinilaya.pemmaraju">Nilaya</option>
        <option value="nishath">Nishath</option>
        <option value="ravikiran.kothamasu">Ravi Kiran</option>
        <option value="swami.sukumaran">Swami</option>
      </select>
    </div>
  </div>
</div>
<button id="submit">Save</button>
&#13;
&#13;
&#13;

参考:jQuery Tip – Getting Select List Values