Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery detect dropdown value is selected even if it's not changed

Using JQuery or JavaScript, I want to detect when a user selects a value, even if they don't change the already selected value.

How can this be accomplished?

I tried -

$('#MyID').select(function(){ /*my function*/ });

and

$('#MyID').change(function(){ /*my function*/ }); //nothing changing, so this fails

But they do not work.

Example - I have a dropdown with a list of years in it with nothing selected, the user selects "1976", I run a function. With "1976" selected, the user clicks on the dropdown again and selects "1976" again, I want to run the function again.

like image 370
A Bogus Avatar asked Jun 26 '13 17:06

A Bogus


1 Answers

all systems go (on second click at least...)

Set a switch to run on selection, and reset the switch after it's captured and/or on blur.

var go = false;//switch off
$('#MyID').on('click',function() {//on click
    if (go) {//if go
        //do stuff here with $(this).val()
        go = false;//switch off
    } else { go = true; }//if !go, switch on
}).on('blur', function() { go = false; });//switch off on blur

made a fiddle: http://jsfiddle.net/filever10/2XBVf/

edit: for keyboard support as well, something like this should work.

var go = false;//switch off
$('#MyID').on('focus active click',function() {//on focus/active
    doit($(this));//do it
}).on('change', function() {
    go=true;//go
    doit($(this));//and doit
}).on('blur', function() { go = false; });//switch off on blur

function doit(el) {
    if (go) {//if go
        //do stuff here with el.val()
        go = false;//switch off
    } else {go=true}//else go
}

made a fiddle: http://jsfiddle.net/filever10/TyGPU/

like image 121
FiLeVeR10 Avatar answered Oct 29 '22 15:10

FiLeVeR10