pistolshrimp
pistolshrimp

Reputation: 1039

jQuery, best way to work with <select>

What is the best way to catch a < select > change event? I have a form that has different input elements but I want to trigger an event only in the case of a < select > change. I don't want to use the ID since there are a lot of selects on the form.

Many thanks in advance!

Upvotes: 4

Views: 8596

Answers (4)

Muleskinner
Muleskinner

Reputation: 14468

The accepted and suggested answers are missing one important point: If the user uses the keyboard (arrow keys or letters for example) to navigate the optionbox the change will not be catched.

You need to add one more event, namely "keydown", and bind it to the control.

Something like this:

$('select.foo').bind('change keyup',function() {
    // do something amazingly clever like  
    alert($(this).val());
});

Upvotes: 2

Tiago
Tiago

Reputation: 9557

You can use the selector "select", like this:

$("select").change(function () {

});

and you can access the select that generated the event using

$(this)

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488584

If you want only some selects in the page to have the change event, you can add a class to them, like so:

<select class='choose_me'>...</select>

<!-- later on in the page... -->

<select class='choose_me'>...</select>

And then you can catch the change event from any of these by doing something like:

$('select.choose_me').change(function() { .... } );

If you want to select all of them, you can just change your selector to be

$('select').change(function() { });

Inside the function, you can refer to the select elements by using $(this), so a code like this:

$('select.choose_me').change(function() {
    alert($(this).val());
});

Will alert the selected option of any <select> tags with a class of choose_me on change.

Upvotes: 10

Sebastian
Sebastian

Reputation: 2942

For a select like this:

<select id="item_select" name="item"> 
    <option>Select an Item</option> 
    <option value="1">Item 1</option> 
    <option value="2">Item 2</option> 
    <option value="3">Item 3</option> 
</select>

you do the following:

    <script type="text/javascript"> 

    $(document).ready(function(){ 
        $("#item_select").change(function() 
        { 
// do your stuff

        }); 
    }); 
    </script>

Now, if you don't want to use the id (although every select in your form could just have its individual ID), you can also use any other CSS selector like ("form select:first-child")

Upvotes: 3

Related Questions