开发者

Event handler on specific select value with jquery

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.


$('#sweets').change(function(){
    var show = $(this).val() == 'Option2';
    $('#showthis').toggle(show);
});


Have you tried this?

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


$('#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' );
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜