使用jQuery,你如何检查选择菜单中是否有一个选项,如果没有,分配一个选择的选项。

(选择生成与一个应用程序的PHP函数的迷宫,我刚刚继承,所以这是一个快速修复,而我得到我的脑袋周围的那些:)


当前回答

不需要使用jQuery:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}

其他回答

我在找类似的东西,发现了这个:

$('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true);

这将查找类中尚未选定选项的所有选择菜单,并选择默认选项(在本例中为“2”)。

我尝试使用:selected而不是[selected],但这不起作用,因为某些东西总是被选中,即使没有任何属性

查看select元素的selectedIndex。顺便说一下,这是一个普通的DOM,不是特定于jquery的。

不需要使用jQuery:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}

我发现了一个很好的方法来检查,如果选项被选中,并选择一个默认时,它不是。

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

如果#some_select没有默认选择选项,则.val()是未定义的

$("#select_box_id").children()[1].selected

这是在jquery中检查一个选项是否被选中的另一种方式。这将返回布尔值(True或False)。

[1]是选择框选项的索引