1

I am wondering how to fire an event in jQuery based on a specific select value. So, for example i have a small select and div like so:

<select id="sweets">
  <option value ="Option1">Option 1</option>
  <option value ="Option2">Option 2</option>
  <option value ="Option3">Option 3</option>
</select>
<div id='showthis'>You have selected option 2</div>

I want to do something like;

if the user select Option 2,

$('#showthis').show();

if the user selects any other option,

$('#showthis').hide();

I am fairly new to jQuery and i'm not sure how to do a change event based on a specic select value. Any help would be greatly appreciated.

3 Answers 3

1
$('#sweets').change(function(){
    var show = $(this).val() == 'Option2';
    $('#showthis').toggle(show);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was after, thank you very much. I knew it involved change(function)), but wasn't quite sure how to grab the specific value i needed. Thanks again.
1

Have you tried this?

$('#sweets').change(function() {
    if($(this).attr('value') == 'Option1') {
        // do something
    } else if($(this).attr('value') == 'Option2') {
        // do something else
    } // etc..
}

Comments

0
$('#sweets').change(function() {
    if( this.selectedIndex === 1 ) {
         $('#showthis').show();
    } else {
         $('#showthis').hide();
    }
});

or better yet:

$('#sweets').change(function() {
    $('#showthis').toggle( this.selectedIndex === 1 );
});

The selectedIndex property is a very fast way to reference the selected option.

Using the toggle()(docs) method you can pass a boolean as a switch argument where true == show and false == hide.

Or to do it by value, you could do this:

$('#sweets').change(function() {
    var val = this.options[ this.selectedIndex ].value;
    $('#showthis').toggle( val === 'Option1' );
});

Comments

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.