Yesterday I was following a tutorial for client-side validation using regular expressions. It worked well for the most part. I cannot figure out what I changed for this to stop working.
Basically, I don't think the form should be submitting at all, even if it passes validation. When I click submit and all fields are empty, they should all show the error message, but only the name field does. With error messages displayed, the form will still submit
HTML
<form>
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" class="form-control" id="contact-name" name="name" placeholder="Enter your name.." onkeyup='validateName()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'>
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'>
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea>
<span class='error-message' id='message-error'></span>
</div>
<button onclick='validateForm()' class="btn btn-default">Submit</button>
<span class='error-message' id='submit-error'></span>
</form>
JS
function validateName() {
var name = document.getElementById('contact-name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
producePrompt('First and last name, please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('contact-phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(phone.length != 10) {
producePrompt('Include area code.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('contact-email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
I understand this isn't set up to actually send anything to PHP. I believe the javascript code should work find as there was nothing changed, but the HTML has.
Add a return to the click event:
<button onclick='return validateForm()' class="btn btn-default">Submit</button>
Then, if fails, function should return false:
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
}
See fiddle
Related
I am trying to tie the code in together.
I recently just made a form and found a captcha on codepen that I wanted to try out
But for some reason I cant get the captcha to validate the form even though it does perform the calculation. Any idea what could be causing the problem in my code? Thanks in advance.
<form
class="form mt-4"
method="POST"
action="action_page.php">
<!-- Name Field -->
<div class="form-group">
<label for="name">Name:</label>
<input
type="text"
name="name"
id="name"
placeholder="Enter Your Name"
class="form-control"
required
/>
</div>
<!-- Email Field -->
<div class="form-group">
<label for="email"
>Email Address:</label
>
<input
type="email"
name="email"
id="email"
placeholder="Enter Your Email"
class="form-control"
required
/>
</div>
<!-- Password Field -->
<div class="form-group">
<label for="password"
>Password:</label
>
<input
type="password"
name="password"
minlength="8"
id="password"
placeholder="Password"
class="form-control"
required
/>
</div>
<!-- Confirm Password Field -->
<div class="form-group">
<label for="confirm_password"
>Confirm Password:</label
>
<input
type="password"
name="confirm_password"
minlength="8"
id="confirm_password"
placeholder="Confirm Password"
class="form-control"
required
/>
</div>
<!-- Telegram API Token Field -->
<div class="form-group">
<label for="telegram_token"
>Telegram API Token:</label
>
<input
type="text"
name="telegram_token"
id="telegram_token"
placeholder="Enter Telegram API Token"
class="form-control"
required
/>
</div>
<!-- Telegram Chat ID Field -->
<div class="form-group">
<label for="telegram_id"
>Telegram Chat ID:</label
>
<input
type="text"
name="telegram_id"
id="telegram_id"
placeholder="Enter Telegram Chat ID"
class="form-control"
required
/>
</div>
<!-- Captcha Field -->
<div class="form-group">
<label>Are you human?</label>
<br />
<label class="submit__control">
<div
class="submit__generated"
></div>
<i
class="fa fa-refresh"
></i>
<span
class="submit__error hide"
>Incorrect value</span
>
<span
class="submit__error--empty hide"
>Required field cannot
be left blank</span
>
</label>
</div>
<!-- Register Button -->
<div class="form-group">
<button
type="submit"
class="btn btn-info btn-block"
>
Register
</button>
var a,
b,
c,
submitContent,
captcha,
locked,
validSubmit = false,
timeoutHandle;
// Generating a simple sum (a + b) to make with a result (c)
function generateCaptcha() {
a = Math.ceil(Math.random() * 10);
b = Math.ceil(Math.random() * 10);
c = a + b;
submitContent =
"<span>" +
a +
"</span> + <span>" +
b +
"</span>" +
' = <input class="submit__input" type="text" maxlength="2" size="2" required />';
$(".submit__generated").html(submitContent);
init();
}
// Check the value 'c' and the input value.
function checkCaptcha() {
if (captcha === c) {
// Pop the green valid icon
$(".submit__generated").removeClass("unvalid").addClass("valid");
$(".submit").removeClass("overlay");
$(".submit__overlay").fadeOut("fast");
$(".submit__error").addClass("hide");
$(".submit__error--empty").addClass("hide");
validSubmit = true;
} else {
if (captcha === "") {
$(".submit__error").addClass("hide");
$(".submit__error--empty").removeClass("hide");
} else {
$(".submit__error").removeClass("hide");
$(".submit__error--empty").addClass("hide");
}
// Pop the red unvalid icon
$(".submit__generated").removeClass("valid").addClass("unvalid");
$(".submit").addClass("overlay");
$(".submit__overlay").fadeIn("fast");
validSubmit = false;
}
return validSubmit;
}
function unlock() {
locked = false;
}
// Refresh button click - Reset the captcha
$(".submit__control i.fa-refresh").on("click", function () {
if (!locked) {
locked = true;
setTimeout(unlock, 500);
generateCaptcha();
setTimeout(checkCaptcha, 0);
}
});
// init the action handlers - mostly useful when 'c' is refreshed
function init() {
$("form").on("submit", function (e) {
e.preventDefault();
if ($(".submit__generated").hasClass("valid")) {
// var formValues = [];
captcha = $(".submit__input").val();
if (captcha !== "") {
captcha = Number(captcha);
}
checkCaptcha();
if (validSubmit === true) {
validSubmit = false;
// Temporary direct 'success' simulation
submitted();
}
} else {
return false;
}
});
// Captcha input result handler
$(".submit__input").on(
"propertychange change keyup input paste",
function () {
// Prevent the execution on the first number of the string if it's a 'multiple number string'
// (i.e: execution on the '1' of '12')
window.clearTimeout(timeoutHandle);
timeoutHandle = window.setTimeout(function () {
captcha = $(".submit__input").val();
if (captcha !== "") {
captcha = Number(captcha);
}
checkCaptcha();
}, 150);
}
);
// Add the ':active' state CSS when 'enter' is pressed
$("body")
.on("keydown", function (e) {
if (e.which === 13) {
if ($(".submit-form").hasClass("overlay")) {
checkCaptcha();
} else {
$(".submit-form").addClass("enter-press");
}
}
})
.on("keyup", function (e) {
if (e.which === 13) {
$(".submit-form").removeClass("enter-press");
}
});
// Refresh button click - Reset the captcha
$(".submit-control i.fa-refresh").on("click", function () {
if (!locked) {
locked = true;
setTimeout(unlock, 500);
generateCaptcha();
setTimeout(checkCaptcha, 0);
}
});
// Submit white overlay click
$(".submit-form-overlay").on("click", function () {
checkCaptcha();
});
}
generateCaptcha();
// Password Match Function
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
It was the function for submit was missing
my javascript won't respond to my id-tag within php code:
else {
echo '<form = "nav-login" method="post" onsubmit="return noEmptyUserFields();" action="includes/login.inc.php">
<input type="text" id="uidz" name="uid" placeholder="Username/e-mail">
<input type="password" id="pwdz" name="pwd" placeholder="password">
<button type="submit" name="submit">Login</button>
</form>
Sign up';
}
But it responds to my javascript which is outside of the php which looks like this:
<form class="signup-form" method="post" onsubmit="return noEmptyUserFields();" action="includes/signup.inc.php">
<input type="text" id="first" name="first" placeholder="Firstname">
<input type="text" id="last" name="last" placeholder="Lastname" >
<input type="email" id="email" name="email" placeholder="E-mail" >
<input type="text" id="uid" name="uid" placeholder="Username" >
<input type="password" id="pwd" name="pwd" placeholder="Password" ></p2>
<button type="submit" name="submit">Sign up</button></form>
How come it won't respond to the id-selector within php?
I have included <script src="includes/javascript.js"></script>
on both.
My javascript looks like this (noEmptyLoginFields) :
if (email.trim().length < 1)
{
alert('Email must be filled out');
return false;
}
else if(pwd.trim().length < 6)
{
alert('Password must contain atleast 6 characters');
return false;
}
else if (first.trim().length < 1)
{
alert('First name must be filled out');
return false;
}
else if (last.trim().length < 1)
{
alert('Last name must be filled out');
return false;
}
else if (uid.trim().length < 1)
{
alert('Username must be filled out');
return false;
}
else return true;
}
function noEmptyLoginFields()
var uidz = document.getElementById('uidz').value;
var pwdz = document.getElementById('pwdz').value;
if (uidz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
else if(pwdz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
}
You seem to be using the same function name for both form validations, which is causing the error. I advise you to handle form validation purely in javascript using event handlers:
document.querySelector("#formId").addEventListener("submit", function() {
// if(...) return false;
});
This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>
I am trying to validate a form using javascript but I can change border color when the if statement looking at the password(login_pass) is not included in the script but when added nothing works. I referred to the bootstrap form validation as well but could not understand why nothing works when I add the second if statement with login_pass.
Here is the form html:
<form id="needs-validation" name="account" action="" method="POST" novalidate>
<div class="form-group" style="margin: auto;">
<label for="user">User Name</label>
<input id="login_uname" type="text" class="form-control" placeholder="User Name" value="" name="user" required>
</div>
<div class="form-group" style="margin: auto;">
<label for="pwd">Password</label>
<input id="login_password" type="password" class="form-control" placeholder="Password" value="" name="pwd" required>
</div>
<button id="login_submit" style="margin-right: 10%; float: right;" type="submit" class="btn btn-default">Log In</button>
</form>
Here is my javascript:
var form = document.getElementById('needs-validation');
var login_user = document.getElementById('login_uname');
var login_pass = document.getElementById('login_pass');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
if(login_user.value === "") {
login_user.style.borderColor = 'red';
} else {
login_user.style.borderColor = 'green';
}
if(login_pass.value === "") {
login_pass.style.borderColor = 'red';
} else {
login_pass.style.borderColor = 'green';
}
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
}
}, false);
Besides the typo in the id of password field you could use ValidityState in your syntax like in the example below. It would be better for handling input errors e.g. a pattern mismatch error.
var form = document.getElementById('needs-validation');
var login_user = document.getElementById('login_uname');
var login_pass = document.getElementById('login_password');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
if (login_user.validity.valueMissing) {
login_user.style.borderColor = 'red';
} else {
login_user.style.borderColor = 'green';
}
if(login_pass.validity.valueMissing) {
login_pass.style.borderColor = 'red';
} else {
login_pass.style.borderColor = 'green';
}
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
}
}, false);
Change
var login_pass = document.getElementById('login_pass');
to
var login_pass = document.getElementById('login_password');
I am having issues with a code I am using to check email validity before sending it off to a database. I have a javascript code that checks the email in the following way:
See if the first email is a valid email address
See if the two email fields match
Here is the relevant parts of the form:
<form action="URLGOESHERE" method="post" name="someName" onSubmit="return validation();" id="formId">
<section class="sectionHeader">
<h2>Contact Information</h2>
<span class="important">*Required Fields</span>
</section>
<section id="contactInfo">
<fieldset>
<legend>Contact Information</legend>
<div id="contact">
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>First Name:</label>
<input type="text" name="firstName" class="imp" size="20" maxlength="25" placeholder="John">
</div>
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>Last Name:</label>
<input type="text" name="lastName" class="imp" size="20" maxlength="25" placeholder="Smith">
</div>
<div class="inputGroupSL">
<span class="left"><label for="org">Company/Group Name:</label></span>
<input type="text" name="org" size="30" maxlength="50" placeholder="Auburn University">
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email"><span class="important">*</span>Email:</label></span>
<input name='email' id='email' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com" />
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email2"><span class="important">*</span>Re-type Email:</label></span>
<input name='email2' id='email2' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com"/>
</div>
<div id="phoneGroup">
<span class="left"><span class="important">*</span>Phone #:</span>
<input name='phone' type='text' class="imp" id="phone" size='12' maxlength='20' placeholder="xxx-xxx-xxxx" />
</div>
<div id="extGroup">
<span class="left">Ext:</span>
<input name='ext' type='text' id="ext" size='12' maxlength='6' placeholder="xxxx" />
</div>
</div>
</fieldset>
</section>
And here is my code that runs onSubmit:
var reEMail=/^\w[\w\-\.]+\#\w[\w\-]+(\.[\w\-]+)+$/;
function validation() {
if (!checkImportant()) {
alert("Please enter information in all fields marked important.");
return false;
}
if (!checkAttendees())
return false;
if (!checkEmail($('#email'),$('#email2')))
return false;
return true;
}
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
function checkAttendees() {
total = 0 + Number($('#numAttend').val());
parts = 0 + Number($('#8').val()) + 0 + Number($('#12').val()) + 0 + Number($('#16').val()) + 0 + Number($('#19').val()) + 0 + Number($('#26').val()) + 0 + Number($('#26').val()) + 0 + Number($('#55').val());
count = 0;
if (total != (parts)) {
alert('Please check to ensure you have entered the correct number of participants.');
count++;
if (count%2 == 0) {
$('#numAttend').focus();
return false;
}
else {
$('#8').focus();
return false;
}
}
return true;
}
function checkEmail(email,email2) {
if (goodEMail2(email)) {
if (email.val() != email2.val()) {
alert("Please check to make sure your email address is correct in both fields!");
email2.focus();
return false;
}
else return true;
}
else {
alert("Please input a valid email address");
setTimeout(function(){
$('#email').focus();
}, 100);
email.select();
return false;
}
return false;
}
function goodEMail2(field) {
return _checkIt2(reEMail, field);
}
function _checkIt2(re, field){
if (!re.test(field.val())) {
field.select();
field.focus();
return false;
}
else return true;
}
As you can see in my main if else statement of my checkEmail function I am having to use setTimeout to delay the focusing on the email field. If I take out the setTimeout, the page will not focus on the element. However, if I take out the setTimeout and change the specified element to the second email field, it works.
The only exception to this is in IE10 (to my testing in FF, Chrome, Safari, and IE10).
I don't really want to use this work around and I don't understand why I need to. Can anyone give me some ideas or answers?
Thanks!
EDIT: Can't seem to get my hack to work now. I'm not sure what it was doing before... so now focus() doesn't work at all on that particular element.
changing:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
to:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if(important[i].value == "") { // drop the jQuery reference, not needed
important[i].focus(); // drop the jQuery reference, not needed
return false;
}
}
return true;
}
worked for me in Chrome