我正在使用Chosen多选框,希望用户选择任何选项后,我能够获取其值并根据该值执行一些功能。
在不使用多选的情况下,可以使用以下代码来获取所选值:
$(".selectId").chosen().change(function(){
selectedValue = $(this).find("option:selected").val();
});
但在多选时,我一再获得第一个已选择的值。请问有人能帮忙找到当前在多选元素中选择的值吗?
我正在使用Chosen多选框,希望用户选择任何选项后,我能够获取其值并根据该值执行一些功能。
在不使用多选的情况下,可以使用以下代码来获取所选值:
$(".selectId").chosen().change(function(){
selectedValue = $(this).find("option:selected").val();
});
但在多选时,我一再获得第一个已选择的值。请问有人能帮忙找到当前在多选元素中选择的值吗?
Chosen documentation 中提到了获取最近更改的变量的参数。
每当进行选择时,Chosen会触发标准DOM事件 (它还会发送一个selected或deselected参数,告诉您哪个选项已更改)。
因此,如果您只想要最近选择或取消选择的选项:
$(".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.
});
简短回答:
你只需要这样做: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
...
});
您的代码已经获得了正确的选定值...但由于它是多选的,您需要使用循环或使用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
});
更新
如果您得到逗号分隔的值,则使用split()
函数。
var values= $(".selectId").val();
$.each(values.split(',').function(i,v){
alert(v); //will alert each value
//do your stuff
}
Chosen documentation提到了获取最近更改的变量参数。
$(".CSS Selector").chosen().change(function(e, parameters) {
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
试一下这个
$('.selectId:selected').each(function(i, selected) {
var value = $(selected).val();
var text = $(selected).text();
});
这是我让它工作的方式。在我的HTML中,我有这个:
<select data-placeholder="Choose a Country..." class="form-control chosen-select" multiple tabindex="4">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="CHINA">CHINA</option>
</select>
然后是 JavaScript
// apply chosen-js to the DOM, and store it in a variable.
var chosen = $(".chosen-select").chosen({
no_results_text: "Oops, nothing found!"
});
// inside the change event, we get the value by calling chosen.val()
chosen.change(function() {
console.log('selected tags are', chosen.val());
});
$(".selectId").val();
这个会给你一个数组吗?如果是的话,你可以循环遍历这个数组并使用其中的每一个元素。 :) - bipen