Jquery 需要单击按钮时出现错误消息
我收到了一份作业,用户必须选择大学校园并单击“继续”按钮。我唯一无法工作的是,当没有选择单选按钮并且单击“继续”按钮时,应该会出现一条错误消息,说明“您尚未选择大学校园,请重试。” 除此错误代码外,我的其他一切都正常工作。我就是不明白。出现一条错误消息,说明“未定义”,该消息来自按钮的单击功能。有人能帮忙吗Jquery 需要单击按钮时出现错误消息,jquery,button,radio-button,Jquery,Button,Radio Button,我收到了一份作业,用户必须选择大学校园并单击“继续”按钮。我唯一无法工作的是,当没有选择单选按钮并且单击“继续”按钮时,应该会出现一条错误消息,说明“您尚未选择大学校园,请重试。” 除此错误代码外,我的其他一切都正常工作。我就是不明白。出现一条错误消息,说明“未定义”,该消息来自按钮的单击功能。有人能帮忙吗 <html> <head> <style> input, label { line-height: 1.5em; } &l
<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>
代替$input[type=radio]:checked.val,尝试检查长度,如下所示:
$(function () {
$("#click").click(function(){
if ($("input[type=radio]:checked").length == 0) {
alert( 'Your message goes here' );
}
})
});
使用.val jQuery时,会提取所选单选按钮的值。由于未选择任何单选按钮,因此未定义。如果使用.length jQuery,则返回与选择器字符串匹配的元素数。在这种情况下,如果未选中任何项,您将得到一个0。如果没有选择单选按钮,则没有应返回其值的元素。这应该可以解释警报的原因。至于防止提交,请查看作为回调参数的事件对象。您可以使用绝对图例。非常感谢你:
$(function () {
$("#click").click(function(){
if ($("input[type=radio]:checked").length == 0) {
alert( 'Your message goes here' );
}
})
});