views:

251

answers:

3

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.com/Selectors) should be used in this case?

+3  A: 

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 compare the previous item with the new selected item.

rahul
A: 

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.

ianhales
A: 

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.com/ijowo

Kobi
This is something I just did and it works well for me.
AnzeR