检查是否使用 jQuery 选择了选项,如果没有选择默认值 [英] Check if option is selected with jQuery, if not select a default

查看:23
本文介绍了检查是否使用 jQuery 选择了选项,如果没有选择默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jQuery,如何检查选择菜单中是否有选择的选项,如果没有,将其中一个选项指定为已选择.

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(选择是在我刚刚继承的应用程序中使用迷宫般的 PHP 函数生成的,所以这是一个快速解决方法,同时我还想了解这些 :)

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

推荐答案

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

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

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

这篇关于检查是否使用 jQuery 选择了选项,如果没有选择默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆