除了我是jquery的初学者之外,我不确定自己做错了什么。我需要通过ajax将这些值发送到服务器,以便在那之后进行进一步的dmas计算,但无法进行验证
<script>
$('#button').click( function() {
$("#form").validate({
rules: {
input_one: {
required: true,
number: true
},
input_two: {
required: true,
number: true
}
},
messages: {
input_one: {
required: "1stinput is empty",
number: "invalid entry in 1st input"
},
input_two: {
required: "2nd input is empty",
number: "invalid entry in 2nd input"
}
},
errorPlacement: function (error, element) {
alert(error.text());
},
}).form();
});
</script>
<form id="form" name="form" method="post" action="">
Input one <input id="input_one" name="input_one" class="required" type="text" /><br><br>
Input Two <input id="input_one" name="input_one" class="required" type="text" /><br><br>
<button class="button" id="plus"> Plus </button>
<button class="button" id="sub"> Minus</button>
<button class="button" id="mul"> Multiply </button>
<button class="button" id="div"> Divide </button><br><br><br> RESULT:
<p id="result"></p>
</form>
您的代码中有重复的名称。将第二个输入名称属性设置为'put_two'。也可以在jQuery validate中使用submitHandler方法。在这里,您将获得所有输入字段的表单一次验证通过。从errorPlacement函数中删除警报,因为在JS代码中使用警报不是一种好的做法。请尝试使用console.log语句。
同时删除按钮点击事件。这里不需要点击处理程序,因为默认情况下,您的按钮将在表单中充当提交。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.js"> </script>
<script>
$(document).ready(function () {
$("#form").validate({
rules: {
input_one: {
required: true,
number: true
},
input_two: {
required: true,
number: true
}
},
messages: {
input_one: {
required: "1stinput is empty",
number: "invalid entry in 1st input"
},
input_two: {
required: "2nd input is empty",
number: "invalid entry in 2nd input"
}
},
errorPlacement: function (error, element) {
console.log(error)
},
submitHandler: function (form) {
console.log('Form Submitted');
// It is optional submit form or use AJAX snippet here to make AJAX call
// form.submit();
}
});
// $('.button').click(function () {
// });
});
</script>
</head>
<body>
<form id="form" name="form" method="post" action="">
Input one <input id="input_one" name="input_one" class="required" type="text" /><br><br>
Input Two <input id="input_one" name="input_two" class="required" type="text" /><br><br>
<button class="button" id="plus" type="submit"> Plus </button>
<button class="button" id="sub" > Minus</button>
<button class="button" id="mul"> Multiply </button>
<button class="button" id="div"> Divide </button><br><br><br> RESULT:
<p id="result"></p>
</form>
</body>
</html>