Remember me function autocomplete is not working using jquery - javascript

$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#modal_login_remember').attr('checked', 'checked');
$('#modal_login_email').val(localStorage.usrname);
$('#modal_login_password').val(localStorage.pass);
} else {
$('#modal_login_remember').removeAttr('checked');
$('#modal_login_email').val('');
$('#modal_login_password').val('');
}
$('#modal_login_remember').click(function() {
if ($('#modal_login_remember').is(':checked')) {
// save username and password
localStorage.usrname = $('#modal_login_email').val();
localStorage.pass = $('#modal_login_password').val();
localStorage.chkbx = $('#modal_login_remember').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<p style="text-align: center"><i>Enter your email ID and password to log in to Help.</i></p>
<div id="errormsg" style="display: none; color:red;text-align: center; padding-bottom: 1.2rem;"> Invalid token or login credentials, please log in again.</div>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" id="modal_login_email" name="modal_login_email" class="form-control" placeholder="Enter email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-unlock-alt"></i>
</span>
<input type="password" id="modal_login_password" name="modal_login_password" class="form-control" placeholder="Password" />
</div>
</div>
<label class="custom-control custom-checkbox">
<input type="checkbox" id="modal_login_remember" class="custom-control-input" />
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Remember me</span>
</label>
<div class="modal-footer">
<input type="button" onclick="login(document.getElementById('modal_login_email').value,document.getElementById('modal_login_password').value);" class="btn btn-primary" value="Login" style="background-color: #19659d; border-color: #19659d;" />
</div>
If a user click on remember checkbox at the time of login, the details should to be saved in localstorage. If user tries to login again user details should autocomplete (if user types few letter of his name, name and password should autocomplete). There is no api for it, so i need to do it from front-end.
The value are getting stored in localstorage but the autocomplete is not working ho to approach it.

You can use this code, and you can define the local storage as an object it's would be nic to have.
$(function() {
if (localStorage.chkbx && localStorage.getItem(chkbx) !=='') {
$('#modal_login_remember').attr('checked', 'checked');
$('#modal_login_email').val(localStorage.getItem(usrname));
$('#modal_login_password').val(localStorage.getItem(pass));
} else {
$('#modal_login_remember').removeAttr('checked');
$('#modal_login_email').val('');
$('#modal_login_password').val('');
}
$('#modal_login_remember').click(function() {
if ($('#modal_login_remember').is(':checked')) {
// save username and password
localStorage.setItem('usrname',$('#modal_login_email').val());
localStorage.setItem('pass',$('#modal_login_password').val());
localStorage.setItem('chkbx', $('#modal_login_remember').val());
} else {
localStorage.setItem('usrname', '');
localStorage.setItem('pass', '');
localStorage.setItem('chkbx', '');
}
});
});

Related

Form is not being submitted in html and javascript

I am trying to save data to a table, but it is supposed to submit if everything is good
JAVASCRIPT:
const formm = document.querySelector('#CreateAccount')
const school = document.querySelector('#skool');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const pwd = document.querySelector('#password');
const conf = document.querySelector('#confpassword');
formm.addEventListener("submit", (event) => {
validateForm();
if(result == true){
formm.submit();
console.log(2);
}else{
event.preventDefault();
console.log(30);
}
console.log(30);
});
function isFormValid(){
const inputscontainers = document.querySelectorAll('.inputs')
let result=true;
inputscontainers.forEach((container) => {
if(container.classList.contains("error")){
return false;
}})
return result;
}
function validateForm(){
if(username.value.trim() == ''){
setError(username, 'Name cannot be empty');
}else if(username.value.trim() < 5){
setError(username, 'Idrc');
console.log(3);
}
else{
setSuccess(username);
}
if(email.value.trim() == ''){
setError(email, 'You forgot to fill in your email.');
}
else if(isEmailValid(email.value)){
setSuccess(email);
}else{
setError(email, "Provide a valid email");
}
if(pwd.value.trim()==''){
setError(pwd, "Password can't be empty");
}else if(pwd.value.trim().length<6 || pwd.value.trim().length>20){
setError(pwd, 'Length must be minimum 6 characters and max 20.');
}else{
setSuccess(pwd);
}
if(conf.value.trim() == ''){
setError(conf, 'This is an empty password');
}else if(conf.value !== pwd.value){
setError(conf, 'Passwords dont match');
}
else{
setSuccess(conf);
}
}
function setError(elementr, errorMessage){
const parents = elementr.parentElement;
parents.classList.add("error");
parents.classList.remove("success");
const paragraph = parents.querySelector('p').textContent = errorMessage;
}
function setSuccess(elementr){
const parents = elementr.parentElement;
parents.classList.add("success");
parents.classList.remove("error");
}
function isEmailValid(email){
const reg =/^(([^<>()[\]\.,;:\s#\"]+(\.[^<>()[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
return reg.test(email);
}
HTML
<form id="CreateAccount" action="techer.php" method="GET">
<div class="main">
<div class="Title">
<h1>Enter your details.</h1>
</div>
<div class="inputs">
<label for="skool">SchoolName:</label>
<input type="text" id="skool" placeholder ="Put the school name" name="skool"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="username">Username:</label>
<input type="text" id="username" placeholder ="Username" name="username">
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="password">Password</label>
<input type="password" id="password" placeholder =" Password" name="password"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="confpassword">Confirm Password</label>
<input type="password" id="confpassword" placeholder =" Confirm Password" name="confpassword"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="email">Email:</label>
<input type="email" id="email" placeholder ="Email" name="email"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<button class="submitbtn" type="submit">Submit</button>
</div>
</div>
</form>
As far as the eye can see, there are no errors, and it is not saving data to my php database, which is worrying. My expected result is for, when everything is correct, the from to be submitted then redirected to a php file! But what is happening, even if everything in the form is correct, it wont submit. Please HELP!!
Try adding, at the end of validateForm function:
return isFormValid();
then in your submit listener, change
validateForm();
to
let result = validateForm();

How to order icon next to a span in HTML with CSS?

I am trying to do something like a verification on contact form, e.g if email does not contain "#" and "." show icon of red X and if the conditions are done show green check mark. I need answer on 2 questions: 1. How to align the icon next to the span and the 2. How to center the form in the middle of the screen? I tried with display:flex, many other floats, positions, aligns and every solution I found in the internet, but I anything had success in setting the icon between different tags and centering the form in the middle of the screen but the only one thing I came to is: link
< script type = "text/javascript" >
$(document).ready(function() {
$('.submit').click(function(event) {
console.log('Clicked button')
var name = $('.name').val()
var email = $('.email').val()
var phone = $('.phone').val()
var message = $('.message').val()
var statusElm = $('.status')
statusElm.empty()
if (email.length > 5 && email.includes('#') && email.includes('.')) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (phone.length > 7 && phone.legth < 14) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (message.length > 20) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
})
}) <
/script>
<div class="mail " id="mail">
<div class="container">
<h3 class="w3l_head w3l_head1">Contact Me</h3>
<p class="w3ls_head_para w3ls_head_para1">send Me a message</p>
<div class="w3_mail_grids">
<form action="https://formspree.io/ntodorov301#gmail.com" method="POST" class="justify-content-center">
<div class="col-md-6 w3_agile_mail_grid">
<span class="input input--ichiro"><input
class="input__field input__field--ichiro" type="text" name="name"
id="input-25" placeholder=" " >
<label class="input__label input__label--ichiro" for="input-25">
<span class="input__label-content input__label-content--ichiro">Your
Name</span>
</label>
</span>
<a class="status" name="status"></a> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro email" type="email" name="Email"
id="input-26" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-26">
<span class="input__label-content input__label-content--ichiro">Your
Email</span>
</label>
</span> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro phone" type="text" name="phone"
id="input-27" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-27">
<span class="input__label-content input__label-content--ichiro">Your
Phone Number</span>
</label>
</span>
</div>
<div class="col-md-6 w3_agile_mail_grid">
<textarea class="message" name="message" placeholder="Your Message"></textarea>
<input type="submit" value="Submit" class="submit">
</div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
The Bootstrap is alredy used on the page. Thus, I recommend you to apply validation feature of the framework instead of creation of custom CSS rules. You could use .is-valid and .is-invalid styles for the controls or constraint validation API within custom validation methods.
The following example will help you to get started. I don't want to post too much code, therefore my form contains a single control.
document.getElementById('emailField')
.addEventListener('input', function(e) {
this.classList.remove('is-valid', 'is-invalid')
if (!isValidEmail(this.value))
this.classList.add('is-invalid');
else
this.classList.add('is-valid');
}, false);
document.getElementById('myForm')
.addEventListener('submit', function(e) {
checkEmail(document.getElementById('emailField'));
if (!this.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add('was-validated');
}, false);
function checkEmail(control) {
if (!isValidEmail(control.value)) {
control.setCustomValidity('The e-mail is invalid.');
console.log(control.validationMessage);
} else {
control.setCustomValidity('');
}
}
function isValidEmail(email) {
return /^[\w!#$%&'*+-\/=\?^_`{|}~](\.?[\w!#$%&'*+-\/=\?^_`{|}~])*#gmail\.com$/i.test(email);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container">
<form id="myForm" novalidate>
<div class="form-group">
<label for="emailField">Email address</label>
<input type="email" class="form-control" id="emailField" aria-describedby="emailHelp" placeholder="Enter email">
<small class="valid-feedback">The e-mail address is valid!</small>
<small class="invalid-feedback">The e-mail address is invalid.</small>
<small id="emailHelp" class="form-text text-muted">Only Gmail is supported</small>
</div>
<button class="btn btn-primary" type="submit">Send</button>
</form>
</div>
The snippet uses .is-invalid and .is-valid classes to indicate validation result while user is inputing e-mail address. In the submit event handler the constraint validation API is used. The forms allows to send only address of Gmail. If you will try to use another domain it throws an error.

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.....
}

Validating all form fields -- function not working correctly

I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.
Thanks
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
<header id="header" class="clear">
<div id="hgroup">
<h1>Support Center</h1>
<h2>Welcome to our website</h2>
</div>
<nav>
<ul>
<li>Home</li>
<li>Our Staff</li>
<li>Location</li>
<li>Help</li>
<li class="last"></li>
</ul>
</nav>
</header>
</div>
</body>
<!-- content -->
<body>
<h1>Help is here!</h1>
<form>
<h1>Should you need assistance, please do not hesitate to contact us:</h1>
<div class="contentform">
<div id="sendmessage"> Your form has been sent successfully. Thank you. </div>
<div class="leftcontact">
<div class="form-group">
<p>Surname<span>*</span></p>
<span class="icon-case"><i class="fa fa-male"></i></span>
<input type="text" name="lastName" id="lastName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>First Name <span>*</span></p>
<span class="icon-case"><i class="fa fa-user"></i></span>
<input type="text" name="firstName" id="firstName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>E-mail <span>*</span></p>
<span class="icon-case"><i class="fa fa-envelope-o"></i></span>
<input type="email" name="emailAddress" id="emailAddress"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Office <span>*</span></p>
<span class="icon-case"><i class="fa fa-location-arrow"></i></span>
<input type="text" name="office" id="office"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Desk <span>*</span></p>
<span class="icon-case"><i class="fa fa-map-marker"></i></span>
<input type="text" name="deskNumber" id="deskNumber"/>
<div class="validation"></div>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<p>Phone number <span>*</span></p>
<span class="icon-case"><i class="fa fa-phone"></i></span>
<input type="text" name="mobilePhone" id="mobilePhone"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Job Number <span>*</span></p>
<span class="icon-case"><i class="fa fa-building-o"></i></span>
<input type="text" name="jobNumber" id="jobNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Computer <span>*</span></p>
<span class="icon-case"><i class="fa fa-info"></i></span>
<input type="text" name="computerNumber" id="computerNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comment-o"></i></span>
<select name="Problem">
<option value="New User">New User</option>
<option value="Delete User">Delete User</option>
<option value="Lost File">Lost File</option>
<option value="New Software Installation">New Software Installation</option>
<option value="Virus Checking">Virus Checking</option>
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<p>A little about your problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comments-o"></i></span>
<textarea name="message" rows="14"></textarea>
<div class="validation"></div>
</div>
</div>
</div>
<button type="submit" class="bouton-contact">Send</button>
</form>
</body>
</html>
</body>
</html>
Code
function validateForm() {
var letters = "[A-Za-z]+$";
var numbers = "^[0-9]+$";
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jobNumber = document.getElementById("jobNumber").value;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var mobilePhone = document.getElementById("mobilePhone").value;
var emailAddress = document.getElementById("emailAddress").value;
var officeNumber = document.getElementById("office").value;
var deskNumber = document.getElementById("deskNumber").value;
var computerNumber = document.getElementById("computerNumber").value;
if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {
if(jobNumber.length == 5 && jobNumber.match(numbers)) {
if(firstName.match(letters) && lastName.match(letters)) {
if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {
if(emailAddress.match(emailReg)) {
alert("Form submitted!");
return true;
}
else {
alert("Please enter a valid email");
return false;
}
}
else {
alert("Please enter a valid mobile number");
return false;
}
}
else {
alert("Please enter a valid first name and last name");
return false;
}
}
else {
alert("Please enter a valid job number");
return false;
}
}
else {
alert("Please enter in all fields");
return false;
}
}
Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several.
Also, the reason the email is the only one working is because the browser is validating the email without using your JS.
First I would ditch all the variables declared and replace it with the form object.
var formObject = document.getElementById('contentform');
Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.
var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
errorList.push('Please enter a valid job number');
isValid = false;
}
Then rinse and repeat for each element required. After that, just return the list and status (isValid).
// this should be on its own at the bottom of your function right before you return
if (!isValid) {
alert(errorList);
// I would add some formatting or preferably display in the form view.
}
return isValid;
html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>
Also, these
if (!isValid) {
alert(errorList);
}
should be removed from each if statement and placed at the bottom after all have been checked.
Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.
//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />
//javascript
function validation()
{
var email = document.getElementById('email').value;
if(email == '' || !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
{
document.getElementById('emailerror').style.display = 'inline';
var error=1;
}
else
{
document.getElementById('emailerror').style.display = 'none';
}
if(error == 1)
{
return false;
}
else
{
return true;
}
}
now your email validation works fine, thanks

Enable next form element with the value of previous

I do need to create a form. In that form I need to enable form element one by one. That mean, If an user entered valid data to first element then I want to autofocus next element and so on.
NOTE: When page is load I want to keep all the elements disable except first element.
This is HTML of my form.
<form role="form" class="banner" method="post" action="">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="name" placeholder="Your Name" class="form-control first-name sequence" autocomplete="off" required>
<label for="name" class="glyphicon glyphicon-user" data-toggle="tooltip" data-placement="left" title="Enter Your Name"></label>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="email" name="email" placeholder="Your Email" class="form-control email_address sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-envelope" rel="tooltip" title="Enter Your Email"></label>
<span class="email-error"></span>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="phone" placeholder="Your Phone Number Eg: xx-xxx-xxx" class="form-control phone-number sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-phone" rel="tooltip" title="Enter Your Phone Number"></label>
</div>
</div>
<div class="element-left">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-date" placeholder="Pick Up Date" class="form-control datepicker sequence" autocomplete="off">
<label for="date" class="glyphicon glyphicon-calendar" rel="tooltip" title="Prefered Charter Date"></label>
</div>
</div>
</div>
<div class="element-right">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-time" placeholder="Pick Up Time" class="form-control timepicker sequence" autocomplete="off">
<label for="time" class="glyphicon glyphicon-time" rel="tooltip" title="Time of Charter"></label>
</div>
</div>
</div>
<p class="form-actions">
<button type="submit" name="submit" class="btn btn-default btn-block">
<span class="btn-orange-inner">Send</span>
</button>
</p>
</form>
This is how I tried it in jQuery:
// form validation
function fakeValidator(event) {
var flag = false;
var $element = $(event.target);
var values = $element.val();
if (values.length >= 3) {
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
flag =true;
} else {
flag =false;
}
if(flag){
//alert('hi');
$element.addClass('valid');
enableNextElement(event);
} else{
alert('hi el');
$element.removeClass('valid');
//$element.addAttr('disabled');
}
}
function validemail(value){
var emailReg ="/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
}
function enableNextElement(event) {
var $element = $(event.target);
if ($element.hasClass('valid')) {
$element.closest('.form-group')
.next('.form-group')
.find('.sequence')
.removeAttr('disabled');
}
}
$('.sequence').on('blur keyup', fakeValidator);
But my problem is, if I entered an invalid email next element is enabling. But I want to enable next element if its a valid email in email field.
Can anybody tell me what is wrong with this?
Thank you.
2 things:
You should return true or false from your email validation function i.e. validemail
Your regex is stored as string, and hence you cannot apply test function on it. Remove wrapping it in " "
Above mentioned changes will give you desired result.
function validemail(value){
var emailReg =/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; //regex
return emailReg.test(value); //use test which returns true or false
}
UPDATE
DEMO
It will still enable the phonenumber because you have validation written in such a way.
Your Validation:
if (values.length >= 3) {
//this is ok for name
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true;
}else{
flag =false;//even though flag is false here
}
}
flag =true; //when it comes to this line it again makes it to true
//and for email along with length>3, valid email address has also to be validated
} else {
flag =false;
}
My workaround
if (values.length >= 3) {
flag =true; //set this first
if($element.hasClass('email_address')) {//then perform other validations
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
} else {
flag =false;
}

Categories

Resources