Reputation: 379
I am using jQuery Chosen to convert my select to multiple select. When I choose second item, it gives me both the selected items when I do $(this).val()
.
I want the value for only the item that I select at that moment.
following is my code.
$("#languageId").chosen().on("change",function() {
alert($(this).val());
});
HTML:
<select id="languageId" multiple >
<option value="Hindi">Hindi</option>
<option value="English">English</option>
</select>
Upvotes: 3
Views: 1220
Reputation: 240938
According to the documentation:
Chosen triggers the standard DOM event whenever a selection is made (it also sends a
selected
ordeselected
parameter that tells you which option was changed).
Therefore you can access the selected
/deselected
property on the params
object that is passed in the change
event callback. In other words, params.selected
/params.deselected
would be the value of the option
element that was just selected/deselected.
$("#languageId").chosen().on("change", function(event, params) {
var value = $(this).val();
var changedValue = params.selected || params.deselected;
// ...
});
Addressing your comment below, you could simply check which property is on the params
object in order to determine whether an option was selected/deselected:
$("#languageId").chosen().on("change", function(event, params) {
if (params.selected) {
console.log('The option: ' + params.selected + ' was selected.');
}
if (params.deselected) {
console.log('The option: ' + params.deselected + ' was deselected.');
}
});
Upvotes: 4