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

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


当前回答

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

<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>

其他回答

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

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

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

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

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

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

<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>
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option

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

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

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

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