Writing some JavaScript so the form does not submit in less the fields have been filled out, and if the user has not, a message pops up saying 'please fill out the name field' or 'please fill out the email field' etc. I am writing a separate function for each field (don't know if that is the right way) and when I add each function to the window.onload, it only pops up with one of the messages. Any advice would be great.
HTML
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p> If your request isn't urgent, drop us a quick line and we'll get back to you within 24 hours </p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name" tabindex="10" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email" tabindex="20" />
</p>
<label for="comments">Comments </label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45" rows="5" tabindex="60" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" tabindex="70" />
</p>
</fieldset>
</form>
<p><span id="errorMessage"></span></p>
<p><span id="errorMessage1"></span></p>
JavaScript
function prepareEventHandlers () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("email").value == "Your Email") {
document.getElementById("errorMessage").innerHTML = "Please provide at least an email address!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function prepareEventHandlersName () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("name").value == "Your Name") {
document.getElementById("errorMessage1").innerHTML = "Please provide a name!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage1").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function start() {
prepareEventHandlers();
prepareEventHandlersName();
}
window.onload = start;
You should use the browser's built-in validation attributes.
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p>If your request isn't urgent, drop us a quick line and we'll
get back to you within 24 hours</p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name"
tabindex="10" required />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email"
tabindex="20" required />
</p>
<label for="comments">Comments</label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45"
rows="5" tabindex="60"
placeholder="PLACEHOLDER WHEN NO MESSAGE IS WRITTEN" required>Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send"
tabindex="70" />
</p>
</fieldset>
</form>
When you try to submit the form, the browser will automatically display nice error messages for you, in the user's language. No JavaScript required.
The reason your code is failing, because
document.getElementById("frmContact").onsubmit = ...
will override any previous onsubmit handler you've added.
You need to use .addEventListener() instead, if you want to add multiple functions.
A more correct way would be to create a single function that does all checks, and attach that as the handler, once.
Both functions are running, but you're overwriting the onsubmit handler for frmContact in your second function. To avoid this, don't assign event handlers that way. Instead, use addEventListener.
document.getElementById("frmContact").addEventListener("submit", function(event) {
if (document.getElementById("email").value == "Your Email") {
// Show message
event.preventDefault(); // Prevent form from submitting
}
});
Note that when you do it this way, you can't prevent the form from submitting by simply returning false. Instead, you have to use the event's preventDefault method.
Related
I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(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);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>
The code appears to be hooked up (like this)
jQuery("#contactForm").validationEngine();
because it will validate and raise an error bubble if:
you tab out of required field without any input
you type at least one character into a field that requires more and then click the submit button
But it will not validate and raise an error bubble if you do nothing at all except click the submit button. In that case, it just submits. Once you click in the field or enter anything at all, it seems to work.
What can I be looking for that I've mis-configured?
The HTML:
<form class = "contactform" id = "contactForm">
<fieldset>
<div class="contactform-name contactform-field">
<label class="contactform-label" for="contactform-name">Name:
<br>
</label>
<input class="validate[required,minSize[8]] contactform-input" type="text" id="contactform-name" name="name" />
</div>
<div class="contactform-email contactform-field">
<label class="contactform-label" for="contactform-email">Email Address:<br></label>
<input value class="validate[required,custom[email]] contactform-input" type="email" id="contactform-email" name="contactform-email" />
</div>
<div class="contactform-text contactform-field">
<label class="contactform-label" for="contactform-text">Message:
<br>
</label>
<textarea class="validate[required,minSize[12]]contactform-input" name="text" id="contactform-text" > </textarea>
</div>
<input class="contactform-button" type="submit" name="submit" value="Send" />
</fieldset>
</form>
The JavaScript (it's running in Meteor):
Template.Contact.rendered = function () {
jQuery("#contactForm").validationEngine();
}
I've never used this engine, but from the docs I found that 'attach' will attach the validator to form.submit. Can it be as simple as that?
https://github.com/posabsolute/jQuery-Validation-Engine#attach
EDIT:
You can also do stuff to the submit-event (if the tip above won't help).
Something like this (not tested, but should put you in the correct path):
Template.templateName.events({
'submit': function(event) {
// Prevent the submit with preventDefault()
event.preventDefault();
// Do something to check the submit etc.
}
});
I'm trying to figure out how to copy a users text input in one form field to another. Specifically, when someone fills in their email address in the contact form, it will be duplicated in the mailing list form.
Both these forms are using ajax so there's no concerns about the input text being lost on submit.
This is the code I have:
<div id="contact_form">
<form name="contact" method="post" action="">
<input type="text" name="name" id="name" size="30" value="Name" class="text-input" />
<label class="error" for="name" id="name_error">Please enter your name.</label>
<br />
<input type="text" name="email" id="email" size="30" value="Email" class="text-input" />
<label class="error" for="email" id="email_error">I need your email.</label>
<br />
<textarea rows="10" cols="30" type="textarea" name="message" id="message" value="Message" class="text-input" ></textarea>
<label class="error" for="message" id="message_error">A message is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit" value="Send" />
</form>
</div>
<div id="details">
<p>some details here, not sure what yet</p>
</div>
<div id="mail_list">
<input type="text" id="mail" value="Your email" name="mail_list" /><input type="submit" name="submit" class="button" id="submit" value="Send" />
</div>
I found this in the Jquery documentation, but couldn't get it to work:
$("#email").optionCopyTo("#mail");
Thanks!
You said you want it in real time. I assume that means while the user is typing, the value should be replicated for each keystroke.
If that's right, try this:
var mail = document.getElementById("mail");
$("#email").keyup(function() {
mail.value = this.value;
});
Or if you want more jQuery:
var $mail = $("#mail");
$("#email").keyup(function() {
$mail.val( this.value );
});
This will update for each keyup event.
I'd probably add a redundant blur event in case there's an autocomplete in the field.
$("#email").blur(function() {
$mail.val( this.value );
});
Since all your fields have unique ids, this is quite straight forward:
$(function() { // <== Doc Ready
$("#email").change(function() { // When the email is changed
$('#mail').val(this.value); // copy it over to the mail
});
});
Try it out with this jsFiddle
.change()
.val()
Is $("#mail") another input box ? It doesn't appear in your HTML (Edit: well it does now, but didn't at first :)
$("#mail").val($("#email").val()) should do what you want.
use keyup and change both.
$("#boxx").on('keypress change', function(event) {
var data=$(this).val();
$("div").text(data);
});
here is the example
http://jsfiddle.net/6HmxM/785/
you can simply do this
$('#mail').text($('#email').val())