如何从多选(select2)输出刚刚选择的值?

时间:2018-02-05 14:02:16

标签: jquery select

我尝试仅输出最后选择的选项,但我遇到了困难:

$("#multipleSelectExample").select2();
$("#multipleSelectExample").on("select2-selecting", function(e) {
  var selected = $(this).val();
  console.log("You just selected Option " + selected);
});
.selectRow {
    display : block;
    padding : 20px;
}
.select2-container {
    width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://select2.github.io/select2/select2-3.5.1/select2.js"></script>
<link href="http://select2.github.io/select2/select2-3.5.1/select2.css" rel="stylesheet"/>


<body>
    <div class="selectRow">
        <!-- Using data-placeholder below to set place holder value versus putting in configuration -->
        <select id="multipleSelectExample" data-placeholder="Select an option" multiple>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
        </select>
    </div>
</body>

jsfiddle.net/n4n5Y/568

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$("#multipleSelectExample").select2();
var selectedLengthPrev = 1;
$("#multipleSelectExample").on("change", function(e) {
  var selectedLengthNow = $('.select2-choices li').length;
  if (selectedLengthNow > selectedLengthPrev) {
    var lastSelected = $('.select2-choices li')[selectedLengthNow - 2];
    var lastSelectedVal = $(lastSelected).find('div').html();
    console.log("You just selected Option: " + lastSelectedVal);
  }
  selectedLengthPrev = selectedLengthNow;
});
&#13;
.selectRow {
  display: block;
  padding: 20px;
}

.select2-container {
  width: 200px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />


<body>
  <div class="selectRow">
    <select id="multipleSelectExample" data-placeholder="Select an option" multiple>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
        </select>
  </div>
</body>
&#13;
&#13;
&#13;

JSFiddle Link