jquery fadeIn and fadeOut not working before click - javascript

i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.

Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.

Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}

Related

Use javascript code in php in function.php file

I write this code for a login form in function.php file in Wordpress:
$name = $_POST['dx'];
$pass = $_POST['SX'];
$submitbutton= $_POST['commit'];
if ( isset($submitbutton) ) {
if( isset($name) && empty($name) ){
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "username is empty";
errorMsg.style.display = "block"; </script>';
}
else if( isset($pass) && empty($pass) ){
$name = "";
$pass = "";
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "password is empty";
errorMsg.style.display = "block"; </script>';
}
}
I got an error Cannot read property 'style' of null
HTML code
<div class="login">
<ul class="errorMessages" id="errorMsg">
<li></li>
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30"
class="keyboardInput" vki_attached="true">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
I want to check the form fields, if fields were empty, show the error messege above the form.
Something like this image:
How can I use script code in right way in PHP? and how can I resolve this error?
<div class="login">
<ul class="errorMessages" id="errorMsg">
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30" class="keyboardInput" vki_attached="true"><img src="http://account.taminm.ir/wp-content/uploads/2020/01/keyboard.png" alt="Display virtual keyboard interface" class="keyboardInputInitiator" title="Display virtual keyboard interface">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
<script type="text/javascript">
const loginWrapper = document.querySelector('.login'),
errorContainer = loginWrapper.querySelector('.errorMessages'),
form = loginWrapper.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const username = form.querySelector('#dx').value.trim(),
password = form.querySelector('#SX').value.trim();
if ( !username ) {
errorContainer.innerHTML = 'username is empty';
} else if (!password) {
errorContainer.innerHTML = 'password is empty';
} else {
form.submit()
}
});
</script>

Pop-up messages during registration

recently started to deal with javascript, now I'm doing a registration page. And at the moment the notification about the incorrect filling of the form is displayed via alert (). How can this be improved so that if you enter incorrectly, you immediately see a hint ?
function valid(form){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker = "Wrong first name";
}else if(!namePattern.test(lName)){
checker = "Wrong last name"
}else if(!passwordPattern.test(password)){
checker = "Wrong password"
}else if(confirmPassword != password){
checker = "Your passwords do not match"
}else if(!emailPattern.test(email)){
checker = "Wrong email"
}
if(checker){
alert(checker);
}
}
<form action="" method="post" name="submit" onsubmit="valid(this)">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" value="submit"/>
</form>
I will be grateful for help)
I suggest you put on input elements onchange function, for example:
<input type="text" name="fName" id="fName" placeholder="Your first name" onchange='validateInput(e)'>
And then you check in function:
function validateInput(e){
var namePattern = new RegExp("^([A-z]{4,20})$");
const value = e.target.value;
if(!namePattern.test(value)){
alert("Wrong first name");
// But instead of alert I would suggest you change the color of the input element in order for the user to see real time that he is entering wrong thing.
//When he enters correct data, input border should be green. This is much more user friendly
}
}
You can every validation check separately like this...
function firstname(value){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
if(!namePattern.test(value)){
checker = "Wrong first name";
}
if(checker){
alert(checker);
}
}
<input type="text" name="fName" id="fName" placeholder="Your first name" onblur="firstname(this.value)">
I suggest you can use jquery validation.
The thing is, you are checking your form on your submit event (which is obviously the event that is trigger when the form is submitted).
You need to add input validation on each of your input fields via certain event listeners.
If you add onchange event listener, your callback validation will fire each time you move your focus to another element (aka blur event).
If you add oninput event listener, your callback validation will fire each time you type something new.
I would recommend taking a look at the answers of this question.
var checker;
function valid(form){
checker = '';
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker += "No first name<br/>";
}
if(!namePattern.test(lName)){
checker += "No last name<br/>"
}
if(!passwordPattern.test(password)){
checker += "No password<br/>"
}
if(confirmPassword != password){
checker += "Your passwords do not match<br/>"
}
if(!emailPattern.test(email)){
checker += "No email<br/>"
}
if(checker){
document.getElementById("hint").innerHTML = checker;
}
}
valid(document.getElementById("form"));
<form id='form' action="return false;" method="post" name="submit" oninput="valid(this)" onsubmit=' return false;'>
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div style='color:red' id='hint'></div>
<input type='submit'/>
</form>
Using the oninput event to run every single time a input is changed. More user friendly by displaying a text tip instead of popups, and shows all errors, not just the first one in the if/elseif loop.
P.S: You seem to have forgotten to add the submit button in your code.
EDIT: Also made it check validation as soon as the page loaded up too.

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Issue in jquery validator popup message

I want to create some popup that will tell user when he doesn't enter name, lastname, number or email.
HTML :
<div class="form-group">
<label class="label-block" for="cname" data-new-placeholder="What is your name?">Ime</label>
<input name="firstName" minlength="3" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block" for="cemail">Email</label>
<input name="ctct" type="email" required="required" required class="texbox">
</div>
</div>
<div class=" col-md-6">
<div class="form-group">
<label class="label-block">Prezime</label>
<input name="lastName" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block">Telefon</label>
<input name="number" type="digits" required class="texbox">
</div>
</div>
JS :
<script src="scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function () {
$("#configuration-form").validate({
messages: {
name: {
required: "Error!"
}
}
});
});
</script>
<script>
$("#commentForm").validate();
</script>
That is my code in html and css... I managed to make my textbox turns red when the email is not ok. how to create that popup text.
It looks like you are using Twitter Bootstrap, and they have a popover feature or alert message that you can use: Bootstrap - popovers
HTML :-
Validation for Email.
<input type="text" id="email">
<input type="submit" onclick="validateEmail()" >
JavaScript Code :-
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
document.getElementById("email").style.backgroundColor = "Red";
return false;
}
}
Working Demo for Email Validation.
I hope it will help you.

Categories

Resources