我有一个表单,用户输入一个 cnic 号码,如果该号码小于 15,则发出一条消息并停止表单提交,但问题是当 cnic
号码小于 15 时,表单提交无法停止超过 15。
<script>
function validateform()
{
var cnic1 = document.getElementById("cnic1").value;
if (cnic1.length < 15)
{
window.alert("Invalid CNIC");
cnic1.focus();
return false;
}
}
</script>
<form class="col s12" action="tabs.php" method="post" enctype="multipart/form-data" name="applyform">
<div class="row">
<div class="input-field col s1"></div>
<div class="input-field col s4"><label>CNIC No. </label>
<font style="color: #ff0000">*</font>
</div>
<div class="input-field col s6">
<input id="cnic1" name="cnic1" type="text" value="<?php echo $RowAcc['cnic'];?>" maxlength="15" placeholder="CNIC #" required>
</div>
</div>
</form>
在 tabs.php
页面上编写的 php 提交代码是否存在问题,这就是表单仍在提交过程中的原因?
最佳答案
您不必返回 false
来停止提交表单。您需要使用事件的 preventDefault()
方法,如果数据有效,则使用 JS 提交表单。像这样:
function validateform(e) { // take the event as parameter
e.preventDefault(); // stop the submission
var cnic1 = document.getElementById("cnic1");
if (cnic1.value.length < 15) {
window.alert("Invalid CNIC");
cnic1.focus();
} else {
form.submit();
}
}
var form = document.getElementsByName('applyform')[0];
form.addEventListener('submit', validateform);
我还使用 JS 添加了监听器,这样您就可以确保事件参数传递到您的验证函数。从表单中删除 onsubmit="..."
。
关于javascript - 使用 JavaScript 时停止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507910/