How to get the current input value which is entering on select 2 input field

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 05:14:00

问题


When i'm first time entering multi select values i got the current entered text value based on below code in jquery

 <select class="form-control select2" multiple="multiple" data-placeholder="Select areas" style="width: 100%;" id="edit_areas" name="area">
 </select>
$(".select2-search__field").val()

$(document).on('keyup',".select2", function (e) {

    var city = $("#add_city option:selected").text();
    var location = $(".select2-search__field").val();});

which works fine.

But on edit when try to enter more values,current entering value is failed to get by using above code its showing empty

Note: Here i'm setting the dropdown dynamically based on user enters

Can anyone help me to resolve this issue.


回答1:


You should use select2 specific methods to get and set the value, once you already converted to the select2.

When you are setting the value (e.g. for edit), use code like following :

$(".select2").select2("val", "Am,WY".split(",")); 

and to get the value, use code like following :

$(".select2").select2('val');

Hope it will resolve your issue (as not sure what is the HTML and code you are having, its just a guess :-))




回答2:


Without seeing your HTML or complete jQuery it's hard to see exactly what you are trying to do. So I have made a stab in the dark.

$(document).ready(function() {
  $('.mrselect').on('change', function() {
    var values = $(this).find('option:selected');
    var fancyPantsArray = [];
    values.each(function() {
      fancyPantsArray.push($(this).val());
    });
    console.log(fancyPantsArray);
  });
});
<select class="mrselect" multiple="multiple" name="mrselect">
  <option value="Mr Option 1">Mr Option 1</option>
  <option value="Mr Option 2">Mr Option 2</option>
  <option value="Mr Option 3">Mr Option 3</option>
  <option value="Mr Option 4">Mr Option 4</option>
  <option value="Mr Option 5">Mr Option 5</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>



回答3:


try this

var nome = $("#select_id").data('select').$dropdown.find("input").val();


or 



$('input.select2-input').val();


来源:https://stackoverflow.com/questions/44307427/how-to-get-the-current-input-value-which-is-entering-on-select-2-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!