I'm using Chosen Multiple Select What I want to do is that if user selects any option I want that value and then I will do some functionality depending on that value.
In chosen without multiple select i can get selected value by using foll. code
$(".selectId").chosen().change(function(){
selectedValue = $(this).find("option:selected").val();
});
But in multiple select I get the first selected value again n again can anybody help me by finding the current selected value in multiple select element??
The Chosen documentation mentions parameters for getting the most recently changed variables.
Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed).
So, if you just want the most recent option selected or deselected:
$(".selectId").chosen().change(function(e, params){
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
Otherwise if you want the whole array to work with you can use:
$(".selectId").chosen().change(function(e, params){
values = $(".selectId").chosen().val();
//values is an array containing all the results.
});
Short answer:
You just do this: var myValues = $('#my-select').chosen().val();
Full example:
If you have a select-multiple like this:
<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>
You can get the selected values in an array to doing the following:
// 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
...
});
your code is gettin the correct selected value.. but since its multiple you need to use loop..or use map
to get the selected value and push it into array..
try this
$(".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
});
updated
if you are getting commaseperated values then use split()
var values= $(".selectId").val();
$.each(values.split(',').function(i,v){
alert(v); //will alert each value
//do your stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With