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>
According to the documentation:
Chosen triggers the standard DOM event whenever a selection is made (it also sends a
selectedordeselectedparameter 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.
Example Here
$("#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.');
}
});
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