当没有从评级表单中选择任何值时,Jquery不会提醒我。会不会是因为selected="selected“实际上被视为jQuery值?
<label for="rating">Rating</label>
<select id="rating" name="rating" />
<option selected="selected" disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
$(document).ready(function(){
// No value for movie_title
if ($('#movie_title').val() == "" ) {
alert ("No Film");
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert ("No actor");
}
// No value for rating
if ($('#rating').val() == "") {
alert ("No Rating");
}
//No value for review
if ($('#review').val() == "") {
alert ("No review");
}
// Focus on first form field.
$("input:text:visible:first").focus();
})发布于 2013-09-19 01:28:26
这是因为如果未指定任何值,则缺省值将为文本。
将值0赋给您的默认选项,并对照该值进行检查:
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>发布于 2013-09-19 01:33:37
$('#rating').val()返回null
添加value属性在Chrome中似乎不起作用,尽管检查null可以。
console.log($('#rating').val()); //null
console.log($('#rating').val() == "0"); //false
console.log($('#rating').val() == null); //true发布于 2013-09-19 01:29:51
您可以使用原生selectedIndex来查找第一个选择的索引- https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
if($('#rating').get(0).selectedIndex === 0){alert("first item")}https://stackoverflow.com/questions/18878552
复制相似问题