让我试着清楚地解释一下自己。我想使用javascript来验证我的表单,一旦填好,我想执行我准备好的Ajax。
这是我想用来验证表单的javascript代码:
function validateForm(frm) {
var age = frm.age.value,
height_ft = frm.height_ft.value,
height_in = frm.height_in.value,
weight = frm.weight.value;
if (isNaN(age) || age == ""){
alert("Please enter your age, numbers only.");
frm.age.focus();
return false;
}
if (isNaN(height_ft) || isNaN(height_in) || height_ft == "" || height_in == "") {
alert("Please enter your height, numbers only.");
return false;
}
if (isNaN(weight) || weight == "") {
alert("Please enter your weight, numbers only.");
frm.weight.focus();
return false;
}
}
现在,下面是我的Ajax代码:
$("#submit").click( function() {
$.post( $("#weightFrm").attr("action"),
$("#weightFrm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
});
});
$("#weightFrm").submit( function() {
return false;
});
现在Ajax代码完美运行,但我想首先验证所有信息,然后在填写完所有内容后提交。将提供任何帮助。
<form id="weightFrm" action="form_submit.php" onclick="return validateForm(this);" method="post">
答案 0 :(得分:0)
这样做
function validateForm(frm) {
var age = frm.age.value,
height_ft = frm.height_ft.value,
height_in = frm.height_in.value,
weight = frm.weight.value;
if (isNaN(age) || age == ""){
alert("Please enter your age, numbers only.");
frm.age.focus();
return false;
}
else if (isNaN(height_ft) || isNaN(height_in) || height_ft == "" || height_in == "") {
alert("Please enter your height, numbers only.");
return false;
}
else if (isNaN(weight) || weight == "") {
alert("Please enter your weight, numbers only.");
frm.weight.focus();
return false;
}else {
$.post( $("#weightFrm").attr("action"),
$("#weightFrm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
});
$("#weightFrm").submit( function() {
return false;
});
}}
答案 1 :(得分:0)
挂钩表单提交而不是提交点击,这样您就可以停止提交表单了。
$('form').on('submit', function(e) {
e.preventDefault();
// Validate here.
// AJAX here.
});
答案 2 :(得分:0)
您可以使用jQuery实时验证表单,如下所示:
<html>
<head>
<title>xyz</title>
<script src="jquery.js"></script>
</head>
<body>
<input type="number" id="age">
</body>
<script>
$(document).ready(function(){
$("#age").on("input",function(){
if(!$.isNumeric($("#age").val()))
{
alert("Age must be numeric!");
}
});
});
</script>
</html>
答案 3 :(得分:0)
您不应在表单中使用onclick
方法,而是使用onsubmit
。您期望的所需行为应更改为以下
$("#submit").click( function(e) {
e.preventDefault();
if(!validateForm(this))
return false;
$.post( $("#weightFrm").attr("action"),
$("#weightFrm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
}
);
return false;
});