Ascherer
Ascherer

Reputation: 8083

Detect how a select was changed

I've got a select field that has logic on keyup, and change, to do stuff. Is there a way to check how it was changed?

For example: I only want the logic to be fired if it was changed by a mouse, or if enter was pressed on it.

For those looking for my exact solution

http://aaronscherer.me/blog/2013/07/31/jquery-roll-to-next-input/

Upvotes: 2

Views: 177

Answers (3)

MaxPowers
MaxPowers

Reputation: 504

Yes - you can listen to any event on any element in the DOM. Check out this fiddle as a starting point. Here is a full list of mouse events and keyboard events you can listen for.

HTML

<select class="my-select-1">
    <option value="1">First</options>
    <option value="2">Second</options>
</select>

<select class="my-select-2">
    <option value="1">A choice</options>
    <option value="2">Another choice</options>
</select>

jQuery

$(document).ready(function() {

    $(".my-select-1").on("click", function(event){
        alert('Do something - click event');
    });

    $('.my-select-2').on('keypress', function(e) {
         var code = (e.keyCode ? e.keyCode : e.which);
         if(code == 13) { //Enter keycode
            alert('Do something - enter key press');
         }    
    });

});

In the example above, $(".my-select-1) is the selector, it could be anything (an ID, a element type, etc). More information on selectors here. The next part, .on("mousedown" attaches an event handler function for one or more events to the selected elements - in this case just a single event, mousedown. More info about on here.

The second example, is a bit more fancy as we have to determine which key was pressed, but other than that uses the same concept. You can find a very lengthy discussion about this on this post, but please note as of 1.7 on is the preferred method (not bind).

Upvotes: 3

Ram
Ram

Reputation: 144689

If you want to know the type of the event, you can simply use the type property of the event object:

$('select').on('change keyup ...', function(event) {
   var type = event.type;
   // ...
}); 

Upvotes: 1

Timur  Shahbanov
Timur Shahbanov

Reputation: 425

You could use onchange event, something like this :

$(document).on('change','#your_select',function() {
    //do something
})

Upvotes: 0

Related Questions