Show <div> when e-mail is validated Jquery - javascript

I would like to show my div when the email isn't validated. And hide it when it is.
This is what I tried, but it isn't working.
$("#fes-email").on("change.validation keyup.validation", function () {
var email = $(this).val();
$("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled')
$("#notification-container").show("slide");
});
}).trigger('change.validation');

You exit the function before you show it.
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled') <---exits function
$("#notification-container").show("slide"); <-- will never be called
});
AND you have a BIGGER problem. On every single change you are binding a submit handler to the form. That is BAD. Take the submit handler OUT of the change event.
(function() {
var isValid = false;
$("#fes-email").on("change.validation keyup.validation", function() {
var email = $(this).val();
isValid = email.length && isValidEmailAddress(email);
}).trigger('change.validation');
$('#fes-form').submit(function() {
if (isValid) {
$("#notification-container").slideUp();
} else {
$("#notification-container").slideDown();
}
return isValid;
});
}());
function isValidEmailAddress(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
#notification-container {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="fes-form">
<label for="fes-email">Email</label>
<input type="text" id="fes-email" name="fes-email" class="validation" />
<input type="submit" />
</form>
<div id="notification-container">Invalid Email</div>

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>

How trigger validation on a textbox when a button is pressed?

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Disable navigating to next page if inputField isn't filled in

I want to prevent the user from accessing the next page if there is an empty
inputField. The alert does show when the field is empty and i click the button, but i can click 'ok' and i get taken to the next page.
<script type="text/javascript">
window.onload = function(){
function checkFilled(inputField) {
if(inputField.value.length > 1) {
return true;
}
else {
alert('field1 is not filled in');
$("#button1").click(function(e){
e.preventDefault();
});
return false;
}
};
document.getElementById('button1').onclick = function() {
var field1 = document.getElementById('field1');
checkFilled(field1);
};
};
</script>
<input type="text" name="field1" id="field1"/>
<a href="nextpage.html">
<div id="button1"></div>
</a>
You used an a tag where the href attribute is set and gets you immediately to the next page, although the inputField is empty. This should do what you want:
window.onload = function(){
function checkFilled(inputField) {
if(inputField.value.length > 1) {
return true;
}
else {
alert('field1 is not filled in');
return false;
}
};
document.getElementById('button1').onclick = function() {
var field1 = document.getElementById('field1');
return checkFilled(field1);
};
};
<input type="text" name="field1" id="field1"/>
<form action="nextpage.html">
<input id="button1" type="submit" value="next">
</form>
Or if you prefer to use an a tag instead of a button:
function checkFilled() {
if(document.getElementById("field1").value.length > 1) {
window.location.href="nextpage.html";
}
else {
alert('field1 is not filled in');
return false;
}
}
<input type="text" name="field1" id="field1"/>
next

Form validation jQuery AJAX [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to made a simple contact form validaton. I´m newbie in Javascript. I tried many tutorials for newbies, hovever, no one tutorial solved my situation, so I´m trying to made my own JS.
But it have two issues:
Form is sent though is empty, although incorrect validation
If validation is failed, it should return all errors on same time
$("#submit").click(function () {
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
function validate() {
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
return false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
return false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
return false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
return false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
return false;
}
return (true);
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form autocomplete="off" id="contact-form" method="post" enctype="multipart/form-data" action="modules/process.php">
<div class="group">
<input type="text" class="move" name="f1" id="f1" /><span class="error" id="f1Err"></span>
<label>Name</label>
</div>
<div class="group">
<input type="text" class="move" name="f2" id="f2" /><span class="error" id="f2Err"></span>
<label>E-mail</label>
</div>
<div class="group">
<input type="text" class="move" name="f3" id="f3" /><span class="error" id="f3Err"></span>
<label>Message subject</label>
</div>
<div class="group">
<textarea type="text" class="move" name="f4" id="f4"></textarea><span class="error" id="f4Err"></span>
<label>Message</label>
</div>
<div class="submit-btn">
<input type="submit" value="SUBMIT" id="submit">
</div>
</form>
Thanks for any ideas.
Lets start with the first click function and the submit functionality, you haven't preventedDefault() to prevent the default method of the submit input you have provided, so you would need to preventDefault() of the event that is being sent in like so
$("#submit").click(function (e) {
e.preventDefault();
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
as the method name shows, its "preventing the default behavior" from running. Next in your validation method, you are returing false after checking a field, so once that one of the validations fails, you are returning. maybe you should return a flag instead so like:
function validate() {
var flag = true;
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
flag = false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
flag = false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
flag = false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
flag = false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
flag = false;
}
return flag;
}
I think should solve your two biggest issues that you pointed out were wrong. (this is not necessarily the best implementation and variable names, i'll leave you to learn and improve on it)
I made a fiddle http://jsfiddle.net/3dnkvtb1. I set errors to false before validating each input, then for each check I set error to true if empty. Make sure to check the console for errors as you go. I added a console.log for each check. Then if no errors, send and clear your form.
$("#submit").click(function(event) {
event.preventDefault();
var hasError = false;
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if ($("#f1").val() == "") {
hasError = true;
$("#f1Err").html("Name is required");
}
console.log($("#f1").val());
if ($("#f2").val() == "") {
hasError = true;
$("#f2Err").html("E-mail is required");
}
console.log($("#f2").val());
if (!re.test($("#f2").val())) {
hasError = true;
$("#f2Err").html("Incorrect e-mail format");
}
console.log($("#f3").val());
if ($("#f3").val() == "") {
hasError = true;
$("#f3Err").html("Message subject is required");
}
console.log($("#f3").val());
if ($("#f4").val() == "") {
hasError = true;
$("#f4Err").html("Message is required");
}
console.log($("#f4").val());
if(!hasError){
console.log('no errors');
//send your form
$.ajax({
url: 'url-here',
type: 'post',
dataType: 'json',
action : 'submit',
data: $('#contact-form').serialize(),
success: function(response) {
console.log(response);
//do something
clear();
}
});
} else {
console.log('something is up');
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
});

Categories