javascript - jQuery : How to check if NO option was explicitly selected in a select box

标签 javascript jquery select

是否可以检测是否没有在选择框中明确选择选项?

我已经尝试过这些方法,但都不起作用:

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

试验 1:

alert($('#select option:selected').length); // returns 1

试验 2:

alert($('#select option[selected=selected]').length); // returns 1

试验 3:

alert($('#select option:selected').attr('selected')); // returns 'selected'

有什么想法吗?

最佳答案

试试这个:

<select id="mySelect">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>

使用这个 JS:

$('#btncheck').click(function(){
     if ($("#mySelect ")[0].selectedIndex <= 0) {
                alert("Not selected");
            }
    else
        alert("Selected");
});

它将检查您的下拉菜单是否被选中。

试试这个 fiddle :http://jsfiddle.net/aPYyt/

希望对您有所帮助!

PS:您必须将第一个值设为默认值。

关于javascript - jQuery : How to check if NO option was explicitly selected in a select box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800261/

相关文章:

javascript - Node - npm-request 中的无效 uri 错误

javascript - 如何在嵌套列表中切换 <li>?

MySQL查询根据特定条件从多个表中选择

javascript - jQuery - 将加载事件附加到动态加载的元素

javascript - 在 ADF 中使用具有动态生成的 ID 的 Jquery

javascript - ClearInterval 对于服务器 api 调用不起作用(但仅有时)

jQuery CSS 方法

JavaScript - 实例化同一类的多个对象

sql - 选择除 null 以外的所有列或 NVL 全部为 null

mysql - 每 x 行组的总和