I have a form where user enter a cnic number if this number is less than 15 then alert a msg and stop the form submission but issue is that form submission cannot stop when the cnic
number is less than 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>
Is there issue in php submission code write on tabs.php
page that's why form still submitting process?
I have a form where user enter a cnic number if this number is less than 15 then alert a msg and stop the form submission but issue is that form submission cannot stop when the cnic
number is less than 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>
Is there issue in php submission code write on tabs.php
page that's why form still submitting process?
- You can use e.stopPropagation(); w3schools./jquery/event_stoppropagation.asp – son pham Commented Nov 15, 2018 at 8:08
4 Answers
Reset to default 8You don't have to return false
to stop the form from being submitted. You need to use the event's preventDefault()
method, and submit the form using JS if the data is valid. Like this:
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);
I also added the listener using JS just so you can be sure the event parameter is passed to your validation function. Remove the onsubmit="..."
from your form.
Call the js function from onchange = "" event, or use any button and call click event. Your js function will work.
return false;
or
event.preventDefault();
You could use the peventDefault() method