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

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


当前回答

简单!默认值应该是第一个选项。完成了!这将引导您使用不引人注目的JavaScript,因为JavaScript不需要:)

低调的JavaScript

其他回答

你们选的人太多了。只需按值选择:

$("#mySelect").val( 3 );

不需要使用jQuery:

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

这是我的函数改变所选的选项。它适用于jQuery 1.3.2

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}
<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>

这个问题已经很老了,有很多观点,所以我只是抛出一些东西,我相信会对一些人有所帮助。

检查一个选择元素是否有任何选定项:

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

或者检查一个select对象是否没有被选中:

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

或者如果你在某种循环中,想要检查当前元素是否被选中:

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

检查一个元素在循环中是否未被选中:

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

这是一些方法。jQuery有许多不同的方法来完成相同的事情,因此通常只需选择一种最有效的方法。