我有一个表单,用户在其中输入一个cnic编号,如果该编号小于15,则会发出消息并停止表单提交,但问题是当cnic
编号小于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="..."
。
从onchange="事件调用js函数,或者使用任意按钮调用click事件。你的js函数会起作用的。
return false;
或
event.preventDefault();
您可以使用peventDefault((方法