问题描述
我应该如何更改我的 javascript 代码以防止它在点击窗口确认()上的取消后链接到另一个页面?
或者我应该使用jQuery来解决这个问题?
请帮忙。谢谢
function checktext() {
var x = document.forms["myTable"]["id"].value;
if (isNaN(x)) {
alert("Please check ID!");
return false;
}
}
function myFunction() {
var check = confirm("Are You Confirm To Submit?");
if (check == true) {
console.log("yes");
}
}
<form name="table_field" id="insert_form" method="post" onsubmit="return checktext()" action="apply.inc.PHP">
<hr>
<h1 class="text-center">Overtime Table</h1>
<hr>
<table class="table table-bordered" id="myTable">
<tr>
<th>ID</th>
<th>Full Name</th>
</tr>
<tr>
<td><input class="form-control" name="id[]" type="text" id="id" required></td>
<td><input class="form-control" name="name[]" type="text" id="name" required></td>
</tr>
</table>
<b>Send To:</b>
<select class="form-control" name="options">
<option value="-----" id="-----" hidden>-----</option>
<option value="Table_A">Table A</option>
<option value="Table_B">Table B</option>
</select>
<input type="submit" name="save" id="save" value="Submit" onclick="myFunction()">
</form>
解决方法
您可以通过 if 条件中的以下代码刷新页面。
window.location.reload()
或
window.location.href = window.location.href;
或
window.location.replace(window.location.href);
,
当您提交表单时,会调用 submit
事件。该事件包含一些存储在 SubmitEvent
对象中的信息和操作。当您通过 onsubmit
属性、onsubmit
属性或通过 addEventListener
侦听事件时,该对象可用。
我强烈建议使用addEventListener
,因为属性版本只是一种旧技术,它不想看起来消亡,并且具有addEventListener
具有的奇怪副作用不是。
如果您不想在提交时提交表单,请调用 preventDefault()
对象上的 event
方法。这将确保您的表单不会在您需要时发送和重新加载页面。
var form = document.getElementById('insert_form');
function onSubmit(event) {
var x = event.target.elements["id"].value;
if (isNaN(x)) {
alert("Please check ID!");
event.preventDefault();
return false;
}
var check = confirm("Are You Confirm To Submit?");
if (check == true) {
console.log("yes");
} else {
event.preventDefault();
}
}
form.addEventListener('submit',onSubmit);
<form name="table_field" id="insert_form" method="post" action="apply.inc.php">
<hr>
<h1 class="text-center">Overtime Table</h1>
<hr>
<table class="table table-bordered" id="myTable">
<tr>
<th>ID</th>
<th>Full Name</th>
</tr>
<tr>
<td><input class="form-control" name="id[]" type="text" id="id" required></td>
<td><input class="form-control" name="name[]" type="text" id="name" required></td>
</tr>
</table>
<b>Send To:</b>
<select class="form-control" name="options">
<option value="-----" id="-----" hidden>-----</option>
<option value="Table_A">Table A</option>
<option value="Table_B">Table B</option>
</select>
<input type="submit" name="save" id="save" value="Submit">
</form>