59

What's the event to bind for when a select form is selected?

I have something like this:

<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>

When Option B is selected, I want some function to run.

So what do I bind,

$("#list").bind("?", function (){
// How do I check if it's option b that's selected here
//blah blah
});

4 Answers 4

107

This jQuery snippet will get you started:

$('#list').change(function() {
    if ($(this).val() === '2') {
        // Do something for option "b"
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

instead of $('option:selected', this).val() you can just use $(this).val()
What about if option A is already selected by default? Such as in the OP's example. You wouldn't have a redirect if you selected option A.
@Pim: See answer from qraqatit below: stackoverflow.com/a/71945665/8398149
5

the event you are looking for is change. more info about that event is available in the jquery docs here: http://docs.jquery.com/Events/change#fn

2 Comments

Works for just about all inputs ... IE misbehaves on radios I think.
yeah IE has a lot of problems with radios and checkboxes - least of all change... i use the click event for those two
1

Although few years late, this actually works also if one select already selected option.

jQuery('#list').on('click', 'option', function () {
    if (jQuery(this).val() === '2') {
        // Do something for option "b"
    }
});

Comments

-1

Maybe select() is a more accurated solution:

$('#list').select(function() {
    if ($(this).val() === '2') {
        // Do something for option "b"
    }
});

1 Comment

"The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes." api.jquery.com/select

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.