我有一个表单,如果该数字小于15,则用户输入一个cnic编号,然后提醒消息,并停止表单提交,但问题是,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提交代码是否存在问题,这就是为什么表单仍在提交过程?
答案 0 :(得分:2)
您不必返回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="..."
。
答案 1 :(得分:0)
从onchange =“”事件中调用js函数,或使用任何按钮并单击click事件。您的js函数将起作用。
答案 2 :(得分:-1)
return false;
或
event.preventDefault();
答案 3 :(得分:-1)
您可以使用 peventDefault() 方法