pioSko
pioSko

Reputation: 551

jQuery Mobile - Triggering already selected option

I'm trying to trigger an event when an already selected option is selected again. I've tried different click and trigger functions but nothing. Please, help.

HTML:

<select id="mySelect" name="mySelect">
    <option class="mylistitem" value="0" selected="selected">Option 0</option>
    <option class="mylistitem" value="1">Option 1</option>
    <option class="mylistitem" value="2">Option 2</option>
</select>​

JS:

$("#mySelect").live("change", function () {
    alert($("#mySelect").val());
});

or http://jsfiddle.net/pioSko/tcWRP/38/

UPDATED: Combined both answers ;) http://jsfiddle.net/pioSko/tcWRP/60/

$(document).delegate('#mySelect-menu li', 'vmousedown', function (event) {
    if ($(this).attr('aria-selected') === 'true') {
        $('#mySelect').trigger('change');
    }
});

Upvotes: 4

Views: 2977

Answers (2)

ianbarker
ianbarker

Reputation: 1254

what I usually do is call $("#mySelect").trigger('change') that will call your code as if the user changed it to the current value

Upvotes: 2

Jasper
Jasper

Reputation: 76003

If you use the native select menu then you'll run into problems quickly. But if you use the jQuery Mobile style select menu then you can bind event handlers to the menu widget since it's made of DIVs and SPANs.

$(document).delegate('#mySelect-menu li', 'vmousedown', function (event) {
    if ($(this).attr('aria-selected') === 'true') {
        alert('That is already selected.');
    }
});​

Here is a demo: http://jsfiddle.net/ys8Kh/

The basic idea is to track clicks on the "option" elements (really list-items) in the custom select menu and check the area-selected attribute to see if the element is already selected. This value gets updated automatically by jQuery Mobile.

Note that #mySelect-menu is the UL element that gets created as the custom select menu interface for a jQuery Mobile select menu. Also notice that vmousedown is a custom jQuery Mobile event that helps work with mouse and touch events. I chose vmousedown because it fires before the value of the select has changed, so we can see if the clicked element was already selected.

Also, to force non-native select widgets, add this attribute to the SELECT tag: data-native-menu="false".

Upvotes: 2

Related Questions