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

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


当前回答

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

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

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有许多不同的方法来完成相同的事情,因此通常只需选择一种最有效的方法。

其他回答

我已经遇到了texotela插件,这让我像这样解决它:

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});

更改选择框上的事件以触发,一旦它发生,则只需拉出所选选项的id属性:-

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});

lencioni的答案是我推荐的。您可以使用“#mySelect option[value='yourDefaultValue']”更改选项的选择器('#mySelect option:last')来选择具有特定值的选项。更多关于选择器的信息。

如果你在客户端大量使用选择列表,请检查这个插件: http://www.texotela.co.uk/code/jquery/select/。如果您想看到更多使用选择列表的示例,请查看源代码。

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

$(".Result").html($("option:selected").text());

虽然我不确定您到底想要完成什么,但这段代码对我来说是有用的。

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

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