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

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


当前回答

if (!$("#select").find("option:selected").length){
  //
}

其他回答

如果你需要显式检查每个选项,看看是否有“selected”属性,你可以这样做。否则使用option:selected你将得到第一个默认选项的值。

var viewport_selected = false;      
$('#viewport option').each(function() {
    if ($(this).attr("selected") == "selected") {
        viewport_selected = true;
    }
});

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

不需要使用jQuery:

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

这是一个快速脚本,我发现工作… . result被分配给一个标签。

$(".Result").html($("option:selected").text());
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option