Check if option is selected with jQuery, if not se

2019-01-03 07:33发布

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

18条回答
闹够了就滚
2楼-- · 2019-01-03 08:06

lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last') to select the option with a specific value using "#mySelect option[value='yourDefaultValue']". More on selectors.

If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.

查看更多
beautiful°
3楼-- · 2019-01-03 08:09

You guys are doing way too much for selecting. Just select by value:

$("#mySelect").val( 3 );
查看更多
叛逆
4楼-- · 2019-01-03 08:13
<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>
查看更多
在下西门庆
5楼-- · 2019-01-03 08:13
if (!$("#select").find("option:selected").length){
  //
}
查看更多
\"骚年 ilove
6楼-- · 2019-01-03 08:14

This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.

To check if a select element has any selected items:

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

or to check if a select has nothing selected:

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

or if you're in a loop of some sort and want to check if the current element is selected:

$('#mySelect option').each(function() {
    if ($(this).is(':selected')) { .. }
});

to check if an element is not selected while in a loop:

$('#mySelect option').each(function() {
    if ($(this).not(':selected')) { .. }
});

These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.

查看更多
三岁会撩人
7楼-- · 2019-01-03 08:15

I already came across the texotela plugin mentioned, which let me solve it like this:

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});
查看更多
登录 后发表回答