Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a multi select dropdown eg:

<select id="myList" multiple="multiple">  
    <option value="1">Opt #1</option>
    <option value="2" selected="selected">Opt #2</option>
    <option value="3" selected="selected">Opt #3</option>
    <option value="4">Opt #4</option>
</select>

If I then selects Opt #4, how do I then only get Opt #4 and not Opt #2 and Opt #3? I know I can get all selected options by this:

var selectedOptions = $("#myList option:selected");

However I only want the option I clicked - Opt #4. Is this possible?

Edit: note that as I manipulate the list inside a change event I can't do it in a click event. Also added missing multiple.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can get it in the click handler for each option element:

$("#myList option").click(function() {
    var clickedOption = $(this);
});

Update

EDIT: As I manipulate the list inside a change event, I can't do it in a click event.

In that case you need to delegate the event using on. Try this:

$("#myList").on("click", "option", function() {
    var clickedOption = $(this);
});

One thing to note, however, is that option elements will not raise click events at all in IE, so neither of the above will not work in that browser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...