Im having some trouble with a simple form. I can't seem to prevent the form from submiting if the fields are empty. Is there an easy way to check if the fields are empty, and then prevent the form submitting?
Here is my html form:
<form method="post" name="simpleForm" id="simpleForm" action="handler.php">
<fieldset>
<legend>Info</legend>
<p><label for="name">Name</label><br>
<input id="name" name="name" class="text" /></p>
<p><label for="email">Email</label><br>
<input id="email" name="email" class="text" /></p>
<legend>Questions</legend>
<p><label for="qs_1">Question 1</label><br>
<input id="qs_1" name="qs_1" class="text" /></p>
<p><label for="qs_2">Question 2</label><br>
<input id="qs_2" name="qs_2" class="text" /></p>
<p><label for="qs_3">Question 3</label><br>
<input id="qs_3" name="qs_3" class="text" /></p>
</fieldset>
<p><input type="submit" name="submit" value="Send" id="sub_btn" /></p>
</form>
Here is my javascript:
$("form#simpleForm").submit(function() {
var name = $('#name').attr('value');
var email = $('#email').attr('value');
var qs_1 = $('#qs_1').attr('value');
var qs_2 = $('#qs_2').attr('value');
var qs_3 = $('#qs_3').attr('value');
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
Use e.preventDefault() to cancel the form submission. If you want to not send an AJAX call, add a condition check. Also, use .val() instead of .attr("value").
$("form#simpleForm").submit(function(ev) {
ev.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var qs_1 = $('#qs_1').val();
var qs_2 = $('#qs_2').val();
var qs_3 = $('#qs_3').val();
//This condition will only be true if each value is not an empty string
if(name && email && qs_1 && qs_2 && qs_3){
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
}
return false; //IE
});
In a general sense if you return false from the submit handler it will prevent the form being submitted in the standard (non-ajax) way, but I see you are already doing this - which you need to if you want to submit it via ajax instead or it will make the ajax call and submit normally.
So all you need for your validation is to put an if test that only makes the $.ajax() call if validation passes:
if (name != "" && etc...) {
$.ajax({ /* your existing ajax code here */ });
}
EDIT: you can also test that there are no blank fields with a single jQuery selector:
if ($("#simpleform :text[value='']").length === 0) {
$.ajax({ /* your existing ajax code here */ });
}
Just have an if check before making ajax request:
if(name != '' && email != '' ...)
{
//send request is true
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
}
else{
return false;
}
Here is a very simple function to make a form invalid if any of the inputs is empty:
function validateForm(data){
var is_valid = true;
$.each(data, function(id, obj) {
if(obj.value === "") {
is_valid = false;
}
});
return is_valid;
}
The data argument should be a json serialized form.
Usage:
var form_data = $( "#my_form" ).serializeArray();
var is_valid = validateForm(form_data);
if(is_valid === true){
// your ajax code
}
Related
im new at this so i couldnt work this out with required fields on script.
html form
<form name="rezform" onsubmit="return validation()" id="loginForm" method="" action="" novalidate="novalidate">
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function insertData() {
var rez_ad = $("#rez_ad").val();
var rez_saat = $("#rez_saat").val();
var rez_gsm = $("#rez_gsm").val();
var rez_tarih = $("#rez_tarih").val();
var rez_email = $("#rez_email").val();
var rez_tip = $("select#rez_tip").val();
var rez_sayi = $("select#rez_sayi").val();
var rez_aciklama = $("#rez_aciklama").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {
rez_ad: rez_ad,
rez_saat: rez_saat,
rez_gsm: rez_gsm,
rez_email: rez_email,
rez_tarih: rez_tarih,
rez_tip: rez_tip,
rez_sayi: rez_sayi,
rez_aciklama: rez_aciklama
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
insert-data.php
/*
Developer: Ehtesham Mehmood
Site: PHPCodify.com
Script: Insert Data in PHP using jQuery AJAX without Page Refresh
File: Insert-Data.php
*/
include('db.php');
$rez_ad=$_POST['rez_ad'];
$rez_saat=$_POST['rez_saat'];
$rez_gsm=$_POST['rez_gsm'];
$rez_email=$_POST['rez_email'];
$rez_tarih=$_POST['rez_tarih'];
$rez_tip=$_POST['rez_tip'];
$rez_sayi=$_POST['rez_sayi'];
$rez_aciklama=$_POST['rez_aciklama'];
$stmt = $DBcon->prepare("INSERT INTO rezervasyon(rez_ad,rez_saat,rez_gsm,rez_email,rez_tarih,rez_tip,rez_sayi,rez_aciklama) VALUES(:rez_ad, :rez_saat,:rez_gsm,:rez_email,:rez_tarih,:rez_tip,:rez_sayi,:rez_aciklama)");
$stmt->bindparam(':rez_ad', $rez_ad);
$stmt->bindparam(':rez_saat', $rez_saat);
$stmt->bindparam(':rez_gsm', $rez_gsm);
$stmt->bindparam(':rez_email', $rez_email);
$stmt->bindparam(':rez_tarih', $rez_tarih);
$stmt->bindparam(':rez_tip', $rez_tip);
$stmt->bindparam(':rez_sayi', $rez_sayi);
$stmt->bindparam(':rez_aciklama', $rez_aciklama);
if($stmt->execute())
{
$res="Rezervasyonunuz tarafımıza ulaşmıştır. En yakın sürede girmiş olduğunuz GSM numaranıza dönüş yapılacaktır.";
echo json_encode($res);
}
else {
$error="Sistemsel bir hata meydana geldi lütfen bir süre sonra tekrar deneyiniz veya iletişime geçiniz.";
echo json_encode($error);
}
?>
So my problem is when i click my send button on html/php data is going mysql even if the inputs and select boxes are empty/not selected. So I have to do it required like in html input or select box. I dont know how to do it properly in javascript. I have found another script but couldnt work it same as like this one. So how can i put required field on this one and if you can explain it the logic it would be nice !
Also do we have a trick for bot protection on javascript form ?
Thanks !
And have a nice day.
You can do something like create a validation function for check whether input fields are empty or not.
function validation() {
submit = true;
var rez_ad = $("#rez_ad").val();
if ( rez_ad.trim() == "" ) {
//Do what ever you like with when empty submission.
alert('Input is empty.');
submit = false;
}
return submit;
}
Then in form on submit return this function.
<form action="" onsubmit="return validation()" method="POST">
function insertData() {
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("select#rez_tip").val();
var rez_sayi=$("select#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
<form name="rezform" onsubmit="return validation()" id="loginForm" method="POST" action="#" >
Since you are using jquery, use $('form').submit() method to return false if the validation is not success. other wise return true.
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
I have created a jsbin page for the reference given by jquery: https://jsbin.com/dokabod/1/edit?html,output
#alex also post the samething. I just corrected some of the errors he had. like return submit. below code working perfectly.
<form action="index.php" onsubmit="return insertData()" method="POST">
<input type="text" name="name" id="rez_ad">
<input type="text" name="name" id="rez_saat">
<input type="text" name="name" id="rez_gsm">
<input type="text" name="name" id="rez_tarih">
<input type="text" name="name" id="rez_email">
<input type="text" name="name" id="rez_tip">
<input type="text" name="name" id="rez_sayi">
<input type="text" name="name" id="rez_aciklama">
<input type="submit" name="" value="Send">
</form>
<div id="message"></div>
function insertData() {
submit = true;
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("#rez_tip").val();
var rez_sayi=$("#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
submit = false;
return submit;
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
I hope you can help me
I have this form
<form action="do_login.php?id=" method=post>
<label>Enter your Frequent Diner ID</label><br>
<div class="shake-id">
<input id="fd-id" class="log-input" type="text" name=loginid value="" maxlength="8" placeholder="Frequent Diner ID" /><br>
</div>
<div class="id-alert" style="display: none;">Your Frequent Diner ID must have 8 digits. Check and try again</div>
<label>Enter your Password</label><br>
<div class="shake-pass">
<input id="pass" class="log-input" type="password" name=password value="" maxlength="20" placeholder="Password" /><br>
</div>
<div class="pass-alert" style="display: none;">Pass wrong</div>
<input type=hidden name=call_from value="login.php">
<input type=hidden name=forward_url value="<?PHP echo urlencode(#$_REQUEST["forward_url"])?>"><br><br>
<input id="test" type=submit value="Login">
</form>
This form execute the file do_login.php (I can not modify this action) but I have added this script before to execute the form:
$('form').submit(function () {
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
$.ajaxSetup({url: "check.php",type: 'POST', async: true, data: 'parametro1='+value1+'¶metro2='+value2+'',
success: function(result){
if (result==("OK")){
return true; //here should execute DO_LOGIN.PHP
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
return false; //here should NOT execute the DO_LOGIN.PHP
}
},
error:function(){
alert('dio error');
}
});
$.ajax();
});
This is working properly but the form is still calling to do_login.php. I want to call the form only if the ajax is successfull... I have added return false; and return true; in the ajax but anyway after process keep executing do_login.php
If you see my first lines of the script them execute another verification and return the form false successful but when I use the same in the ajax the return false looks like it doesnt work
Thanks in advance
It is because the ajax request is asynchronous. So the form submitwon't wait for the ajax request to complete and return true/false, since the default action is not prevented the form is submitted.
The solution is to prevent the form submit in the submit handler, then in the ajax handler if the request is successfull then call the submit again.
$('form').submit(function (e) {
//stop form from submitting
e.preventDefault();
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
var frm = this;
$.ajax({
url: "check.php",
type: 'POST',
data: 'parametro1=' + value1 + '¶metro2=' + value2 + '',
success: function (result) {
if (result == ("OK")) {
frm.submit();
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
}
},
error: function () {
alert('dio error');
}
});
});
Also note that I have removed the use of ajasSetup as it is not really needed, just use $.ajax() directly
Use e.preventDefault();
Place this just after you form submit function.
I am trying to validate a form via jquery but after I hit the submit button the message appears, focus works, but only for 1 ms after message disappears and field looses focus.
Jquery Ajax
$(document).on('submit','.subscribe',function(e) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#sname").val();
var email = $("#semail").val();
if( name == "" ) {
$("#submess").html('Please enter your name in the required field to proceed.');
$("#sname").focus();
}
else if( email == "" ) {
$("#submess").html('Please enter your email address in the required email field to proceed. Thanks.');
$("#email").focus();
}
else if(reg.test(email) == false) {
$("#submess").html('Sorry, your email address is invalid. Please enter a valid email address to proceed. Thanks.');
$("#email").focus();
}
else
{
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
$("#submess").html(output);
}
});
}
});
HTML
<form name="subscribe" class="subscribe">
<div id="submess"></div>
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
Where am i mistaking.
Add
e.preventDefault();
After
$(document).on('submit','.subscribe',function(e) {
Your page is reloading, that's the problem.
i.e.
$(document).on('submit','.subscribe',function(e) {
e.preventDefault();
// some more stuff
}
Working fiddle
I have a comment form which insert data to a database upon submitting. Following is the code;
function reloadRecaptcha() {
var publicKey = "*************************************";
var div = "recap";
Recaptcha.create(publicKey,div,{theme: "white"});
return false;
}
function validateForm() {
var x=document.forms["cmnts"]["name"].value;
if (x==null || x=="") {
jAlert('Please enter your name', 'Error');
return false;
}
var x=document.forms["cmnts"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
jAlert('Please enter a valid email address', 'Error');
return false;
}
var x=document.forms["cmnts"]["comment"].value;
if (x==null || x=="") {
jAlert('Please enter a comment', 'Error');
return false;
}
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
}
}
});
}
Everything (such as form validating works fine except when I hit the submit button, the comment is posted no matter the reCAPTCHA is correct or not. Right before the page starts navigating, I see the alert message. I'm using jAlert to display alert messages. Following is the form;
<h4>Leave your comment</h4>
<form action="blog?post=".$_GET["post"]."#comments" onsubmit="return validateForm();" name="cmnts" method="post">
<div class="form_row">
<label>Name</label><br />
<input type="text" class="tbox" name="name" title="Type your name"/>
</div>
<div class="form_row">
<label>Email (not visible to others)</label><br />
<input type="text" class="tbox" name="email" title="Type your email" />
</div>
<div class="form_row">
<label>Comment</label><br />
<textarea name="comment" class="tbox" rows="6" title="Type your comment" ></textarea>
<p>You may use following HTML tags and attributes: <b> <cite> <del> <i> <u></p>
</div>
<div class="form_row" style="height:80px;">
<label>Captcha</label><br />
<div id="recap"></div>
<p>I must make sure that you're <i>not</i> a spammer or a bot</p>
<div style="clear:both;">
</div>
<input value="Comment" id="submit" name="submit" class="submit_btn float_l" type="submit">
</form>
The <body> tag has an onload event return reloadRecaptcha();
So why doesn't the form get submitted before validating the reCAPTCHA?
This happens because validateForm() does not return anything from the ajax call. You should have a variable like isCaptchaValidated, and set that inside the success() of ajax, and then return that variable after the ajax like below:
var isCaptchaValidated = false;
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
} else {
isCaptchaValidated = true;
}
}
});
return isCaptchaValidated;
By the way, ajax means Asynchronous JavaScript and XML, so I would go against setting async: false.
I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');