最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - jQuery - select item just clicked - Stack Overflow

matteradmin5PV0评论

I would like to know which item in select list was last clicked

I have select drop down like this

<select id="selectId" multiple="multiple" onchange="">
<option value=1>Value 1</option>
<option value=2>Value 2</option>
<option value=3>Value 3</option>
<option value=4>Value 4</option>
</select>

I would like to know, which item from select was last clicked and if it is now selected or not. Which jQuery selector () should be used in this case?

I would like to know which item in select list was last clicked

I have select drop down like this

<select id="selectId" multiple="multiple" onchange="">
<option value=1>Value 1</option>
<option value=2>Value 2</option>
<option value=3>Value 3</option>
<option value=4>Value 4</option>
</select>

I would like to know, which item from select was last clicked and if it is now selected or not. Which jQuery selector (http://docs.jquery./Selectors) should be used in this case?

Share Improve this question asked Oct 15, 2009 at 11:22 AnzeRAnzeR 6004 gold badges11 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You can use

$('#selectId option:selected');

to get the selected option

See

:selected

Wire an onclick event to select and store the clicked item. When a new click occurs pare the previous item with the new selected item.

Try using the click event on the <option> element, this can tell you is the last option was selected or not (you can set this to a variable):

var lastOption;

$('option').click(function(){
    lastOption = $(this);
    var lastIsSelected = lastOption.is(':selected');
    var lastText = lastOption.text();
    // ...
});

See working code here: http://jsbin./ijowo

I would have a look at the selectBoxes plugin for Jquery (http://www.texotela.co.uk/code/jquery/select/)

It's very good for this sort of thing.

Example

jQuery('#selectId').selectedOptions().each( function () {
    alert(this.text());
});

That would give you an alert with the text of each selected option. As stated above, you could monitor the selected options using the change event.

Post a comment

comment list (0)

  1. No comments so far