I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option’s text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options – it will return their text too. As example, if i had already selected the “Second” option, after choosing “Fourth” one, alert would bring me this – “SecondFourth”. So is there any short, simple way with jQuery to get only the “current” selected option’s text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn’t in there, like this:
Give it a try here, When you call
.val()on a<select multiple>it returns an array of the values of its selected<option>elements. We’re simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1if not found) then that’s the new value. After that we’re just using an attribute-equals selector to grab the element and get its.text().If the
value=""may contains quotes or other special characters that would interfere with the selector, use.filter()instead, like this: