简体   繁体   中英

jquery onchange select option not working

Currently my code looks like this,

$("#select").change(function() {
    var thes = $(this).attr('value');
    var next = $('option[:selected]').next().attr('value');
    alert(next);
});

and my select looks like this

<select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

I tried using alert the variable thes and it pops up but when I use the variable next it won't. What is wrong with my code? Please help.

Change

'option[:selected]'

To

'option:selected'

So:

$("#select").change(function() {
    var thes = $(this).attr('value');
    var next = $('option:selected').next().attr('value');
    alert(next);
});

Check this fiddle

Please note that this would give the next() for the last index as undefined . You may want to handle that appropriately.

Read more on the :selected selector here

You missed this

var next = $('option:selected').next().attr('value');

JSFIddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM