[英]Form validation with SELECT field using Jquery
Jquery Isn't alerting me when their is no value selected from the Rating form. 当没有从“评分”表单中选择它们的值时,jQuery不会提醒我。 Would it be because selected="selected" is actually being seen as a value to 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();
})
That's because the default value will be the text if no value is specified. 这是因为如果未指定任何值,则默认值为文本。
Give a value of 0
to your default option and check against that: 将默认值设为
0
,然后进行检查:
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
$('#rating').val()
returns null
: $('#rating').val()
返回null
:
http://jsfiddle.net/KFpFq/ http://jsfiddle.net/KFpFq/
Adding a value
attribute doesn't appear to work in Chrome, though checking for null
does. 尽管检查是否为
null
,但在Chrome中似乎无法添加value
属性。
console.log($('#rating').val()); //null
console.log($('#rating').val() == "0"); //false
console.log($('#rating').val() == null); //true
您可以使用本机selectedIndex
查找第一个选择的索引-https: //developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
if($('#rating').get(0).selectedIndex === 0){alert("first item")}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.