使用选择的jquery插件获取每个选定的值

问题描述 投票:13回答:5

我正在使用选择多个选择我想要做的是,如果用户选择任何我想要该值的选项,那么我将根据该值执行一些功能。

在没有多重选择的情况下,我可以通过使用foll获得所选值。码

$(".selectId").chosen().change(function(){
     selectedValue = $(this).find("option:selected").val();
});

但是在多个选择中我再次获得第一个选定的值n再次可以通过在多个select元素中找到当前选择的值来帮助我吗?

javascript jquery jquery-chosen
5个回答
20
投票

Chosen documentation提到了获取最近更改的变量的参数。

无论何时进行选择,Chosen都会触发标准DOM事件(它还会发送一个选定或取消选择的参数,告诉您哪个选项已更改)。

因此,如果您只想选择或取消选择最新选项:

$(".selectId").chosen().change(function(e, params){
 // params.selected and params.deselected will now contain the values of the
 // or deselected elements.
});

否则,如果您希望整个数组可以使用,您可以使用:

$(".selectId").chosen().change(function(e, params){
 values = $(".selectId").chosen().val();
 //values is an array containing all the results.
});

13
投票

简短回答:

你这样做:var myValues = $('#my-select').chosen().val();

完整示例:

如果您有这样的选择倍数:

<select id="my-select" class="chzn-select" multiple data-placeholder="Choose one or more values...">
  <option value="value1">option1</option>
  <option value="value2">option2</option>
  <option value="value3">option3</option>
</select>

您可以在数组中获取所选值以执行以下操作:

// first initialize the Chosen select
$('#my-select').chosen();

// then, declare how you handle the change event
$('#my-select').chosen().change(function(){
    var myValues = $('#my-select').chosen().val();

    // then do stuff with the array
    ...
});

1
投票

你的代码是正确的选择值...但是因为它的多个你需要使用loop..or使用map来获取所选的值并将其推入数组..

试试这个

 $(".selectId").chosen().change(function(){
    var  selectedValue = $.map( $(this).find("option:selected").val(), function(n){
              return this.value;
       });
    console.log(selectedValue );  //this will print array in console.
    alert(seletedValue.join(',')); //this will alert all values ,comma seperated
});

更新

如果你得到逗号分隔值,那么使用qazxsw poi

split()

0
投票

试试这个

 var values=  $(".selectId").val();
 $.each(values.split(',').function(i,v){
     alert(v); //will alert each value
     //do your stuff
 }

0
投票

$('.selectId:selected').each(function(i, selected) { var value = $(selected).val(); var text = $(selected).text(); }); 提到了获取最近更改的变量的参数。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.