在我的表单中,我试图运行一个javascript函数来比较2个文本框值。另外,在同一个按钮中,我正在尝试执行提交操作以将表单数据保存到数据库并重定向到下一页。 JS函数工作正常,它会生成错误输入的警报,但是一旦我点击警报。它将重定向到下一页而不将表单数据保存到DB。谁能告诉我如何制止这个?
我想这样做:
function check(){
var fistInput = document.getElementById("total").value;
alert(fistInput);
var secondInput = document.getElementById("amount").value;
if(fistInput === secondInput)
{
alert("Good");
}
else if(fistInput > secondInput)
{
alert("Please input correct value");
}
else
{
alert("Please input correct value");
}
}

<form class="form-horizontal" action="print-receipt.php" method="post" name="myform" autocomplete="off" >
<input type="text" id="total" placeholder="Total Amount" name="total" required>
<input type="text" id="amount" placeholder="Total" name="amount">
<button type="submit" name="submit" onclick="check()" >Submit</button>
</form>
&#13;
答案 0 :(得分:0)
表单数据无效时使用event.preventDefault()
,以防止提交表单。
而不是onclick
按钮上的type='submit'
,而是在onsubmit
元素上使用<from>
处理程序。您可以将event
传递给您的函数,如下所示:
<form onsubmit='check(this)'></form>
function check(event){
var fistInput = document.getElementById("total").value;
alert(fistInput);
var secondInput = document.getElementById("amount").value;
if(fistInput === secondInput)
{
alert("Good");
}
else if(fistInput > secondInput)
{
event.preventDefault();
alert("Please input correct value");
}
else
{
event.preventDefault();
alert("Please input correct value");
}
}
<form class="form-horizontal" action="print-receipt.php" method="post" name="myform" autocomplete="off" onsubmit="check(this)">
<input type="text" id="total" placeholder="Total Amount" name="total" required>
<input type="text" id="amount" placeholder="Total" name="amount">
<button type="submit" name="submit" >Submit</button>
</form>
答案 1 :(得分:0)
试试这个:
var form = document.getElementById("f");
function check(){
var fistInput = document.getElementById("total").value;
alert(fistInput);
var secondInput = document.getElementById("amount").value;
if(fistInput === secondInput) {
alert("Good");
form.action = "print-receipt.php";
}
else if(fistInput > secondInput) {
alert("Please input correct value");
form.action = "";
}
else {
alert("Please input correct value");
form.action = "";
}
}
&#13;
<form id="f" class="form-horizontal" action="" method="post" name="myform" autocomplete="off">
<input type="text" id="total" placeholder="Total Amount" name="total" required>
<input type="text" id="amount" placeholder="Total" name="amount">
<button type="submit" name="submit" onclick="check()" >Submit</button>
</form>
&#13;