我已经被分配给一个用户必须选择一个大学校园并单击“继续”按钮的任务。唯一让我无法工作的是,当没有选择单选按钮并点击“继续”按钮时,应该会出现一条错误消息,即“您尚未选择大学校园,请再试一次”。
除了这个错误代码之外,我还能让其他所有东西都正常工作。我只是看不懂。出现一条错误消息,说明“未定义”,该消息来自按钮的单击函数。有人能帮忙吗?
<html>
<head>
<style>
input, label { line-height: 1.5em; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form>
<div>
<input type="radio" name="university" value="Ah, we are not on the same site" id="Belfast">
<label for="Belfast">Belfast</label>
</div>
<div>
<input type="radio" name="university" value="Yeah, we are on the same campus" id="Jordanstown">
<label for="Jordanstown">Jordanstown</label>
</div>
<div>
<input type="radio" name="university" value="Ah, we are not on the same site" id="Coleraine">
<label for="Coleraine">Coleraine</label>
</div>
<div>
<input type="radio" name="university" value="Ah, we are not on the same site" id="Magee">
<label for="Magee">Magee</label>
</div>
<div id="log"></div>
</form>
<input type="button" value="Continue" id="click">
</body>
</html>
<script>
$(function () {
$("#click").click(function () {
alert($("input[type=radio]:checked").val());
})
});
</script>发布于 2013-03-07 15:43:05
http://jsfiddle.net/VMLg9/
$("#click").click(function(){
my_val = $("input[type=radio]:checked").val();
if( my_val === undefined){
alert("MY_VALIDATION_ERROR");
} else {
alert($("input[type=radio]:checked").val());
}
})发布于 2013-03-07 15:43:45
与$("input[type=radio]:checked").val()不同,尝试检查长度,如下所示:
$(function () {
$("#click").click(function(){
if ($("input[type=radio]:checked").length == 0) {
alert( 'Your message goes here' );
}
})
});使用.val()时,jQuery将提取所选单选按钮的值。由于没有选择单选按钮,您将得到undefined。如果使用.length,则jQuery返回与选择器字符串匹配的元素数。在这种情况下,如果没有检查,您将得到0。
https://stackoverflow.com/questions/15275252
复制相似问题