Let’s say that I have a multiple select field like this:
<select id="foodlist" multiple="multiple">
<option selected="selected" value="59">Apple</option>
<option value="61">Orange</option>
<option selected="selected" value="1">Goat</option>
<option value="2">Chicken</option>
<option selected="selected" value="46">Rice</option>
</select>
When an option is selected, no prompt should be given. However, if an option is deselected, I want the user to Confirm their deselection. I started implementing this using jQuery in the change function like this:
$("#foodlist").change(function () {
//check to see if we are selecting or deselecting an option
//I only want to do the next step if we are deselecting an option
if (!confirm("Are you sure you want to remove: " + $(this).text() + "?")) {
//re-select the option that was deselected because the user changed their mind
}
});
My main problem is that the $(this) selector in the change function refers to the entire list when I really want the item that was clicked so that I can see if it was selected/deselected and get the value. Is there a jQuery selector for this? How can I do this?
You can try to attach a
clickevent handler onoptionelement and then check if it is selected or not. Try thisWorking Demo