是否可以检测是否没有在选择框中明确选择选项?
我已经尝试过这些方法,但都不起作用:
<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/