$('#mySelectBox option').each(function() {
if ($(this).isChecked())
alert('this option is selected');
else
alert('this is not');
});
Apparently, the isChecked
doesn't work. SO my question is what is the proper way to do this?
Thanks.
You can get the selected option this way:
LIVE DEMO
But if you want to iterate all the options, do it with
this.selected
instead ofthis.isChecked
which doesn't exist:LIVE DEMO
Update:
You got plenty of answers suggesting you to use this:
$(this).is(':selected')
well, it can be done a lot faster and easier withthis.selected
so why should you use it and not the native DOM element method?!Read Know Your DOM Properties and Functions in the
jQuery
tag infoYou can use this way by jquery :
If you need to check option selected state for specific value:
If you only want to check if an option is selected, then you do not need to iterate through all options. Just do
Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to
$('#mySelectBox').val() != null
If you're not familiar or comfortable with
is()
, you could just check the value ofprop("selected")
.As seen here:
Edit:
As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.
appears to work just as well! Thanks gdoron.
Consider this as your select list:
then you check selected option like this: