This is really throwing me for a loop.
I had this form successfully validating with my javascript by calling onsubmit="return validateForm()" when my validateForm function was inside a global variable. Unfortunately, once I started trying to debug IE8, I kept getting errors for having a global variable and I decided to make it a global function instead...
Now I can't seem to get it to trigger at all. -_-
(And yeah—I've actually prefixed it in testing to make sure it wasn't conflicting due to being global.)
From what I can tell, I'm doing the epitome of a basic form. This method is the one shown on w3schools, and it works for them, so... what gives?
My form:
<form name="emailus" id="emailus" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validateForm()">
<a href="mailto:example#email.com">
<h3><i class="icon-envelope-alt icon-large"></i>Send us an email<span>: example#email.com</span></h3>
</a>
<div class="half">
<fieldset class="name">
<label for="cf_name">Name <span>*</span></label>
<input type="text" id="cf_name" name="cf_name" class="textualformfield" placeholder="Jane Doe" pattern="^[a-zA-Z'\s]+$">
</fieldset>
<fieldset class="emailaddress">
<label for="cf_email">E-mail <span>*</span></label>
<input type="text" id="cf_email" name="cf_email" class="textualformfield" placeholder="janedoe#email.com" pattern="[a-z0-9!#$%\x26'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%\x26'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b">
</fieldset>
<fieldset class="phonenumber">
<label for="cf_phonenumber">Phone</label>
<input type="tel" id="cf_phonenumber" name="cf_phonenumber" class="textualformfield" placeholder="555-555-5555">
</fieldset>
<fieldset class="eventdate">
<label for="cf_eventdate">Event Date</label>
<input type="text" id="cf_eventdate" name="cf_eventdate" class="textualformfield" placeholder="May 25th, 2012">
</fieldset>
<fieldset class="location">
<label for="cf_location">Location</label>
<input type="text" id="cf_location" name="cf_location" class="textualformfield" placeholder="The Church">
</fieldset>
</div>
<div class="half">
<textarea name="cf_message" class="textualformfield" placeholder="Your Message"></textarea>
</div>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
My javascript function, located outside of (document).ready so that it should be able to be called:
function validateForm() {
window.alert("I'm activating!");
var valid = true;
jQuery('p.validationhelpers').remove();
if (document.emailus.cf_email.value === '') {
jQuery('.emailaddress').append("<p class='validationhelpers'>Please enter an email address.</p>");
jQuery('.emailaddress>input').focus();
valid = false;
}
if (document.emailus.cf_name.value === '') {
jQuery('.name').append("<p class='validationhelpers'>Please enter your name.</p>");
jQuery('.name>input').focus();
valid = false;
}
return valid;
}
Instead, it just submits...
I feel like this is a dumb problem. I've tried replacing the onsubmit's content with return validateForm();, return false; return validateForm() (which indeed returned false and prevented submission), return validateForm(); return false();, and validateForm() and validateForm();.
>_<
SOLUTION: bjornarvh found the real cause from debugging the actual site. I'm highlighting it here because the real answer is within the comments of the answer marked as Solved.
Turns out I was missing a closing bracket for one of my functions in javascript, which was causing the validateForm function to be wrapped within (document).ready, which made it inaccessible to onsubmit. Accidental scope issue!
JavaScript is case sensitive, so you need to add
onsubmit="return ValidateForm()"
instead of
onsubmit="return validateForm()"
Related
I'm new with Javascript and I'm learning by myself. I have a problem with a form on my page. I just want to test with a simple javascript code that I can manipulate my input "type=submit" by adding a function to it to console.log a string when the form is submitted (I watched it on a video and I wanted to do it by myself).
Here is my code:
(function() {
"use strict";
document.getElementById('enviar').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
and this is my HTML code:
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
The problem that I'm having here is that is not working at all.. my ID element is selected properly but I don't know what is wrong with my code. I created a variable and console my ID selected to see if I was getting the right element from the DOM and I'm getting in the console the right input element. please if someone knows why is not working.
plus: On my text input field I have a regular expression but I'm not getting the output I want.. the goal is that the user has to write at least two names (First and Last), so when they write just one it will be incorrect.. the problem that I'm having with this regular expression if when someone writes more than two names (First, Middle and Last) I DON'T want to make that an incorrect answer because technically is correct. So I need to make a better regular expression to get that result (when the user writes two or more names, not just two) but I don't know too much about Regular Expressions.
You are getting the element with the id enviar which is the submit button element. You need to be querying based on the form's element id which is escribenos. Try running the snippet below and you can see that it has the expected outcome.
(function() {
"use strict";
document.getElementById('escribenos').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
Okay, I spent all morning trying to solve this, and despite the fact that it seems to have been a problem for a couple years, I couldn't find a solution that worked. I've seen other people on Stack Overflow ask this question, but none of them had working answers.
My Angular app's login form works fine, but the remember password dialog won't pop up in either Chrome or Opera. It does work in Firefox. I understand WHY it doesn't work, but my users are complaining and I need to fix it. What can I do?
<form name="loginForm" ng-submit="login(user)">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Email" ng-model="user.email">
</div>
<div class="input-group">
<input type="password" name="password" class="form-control" placeholder="Password" ng-model="user.password">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
Edit:
Okay, from a couple different answers that didn't work, I was able to piece together something that finally did, which was simply to turn it into an entirely normal HTML form where the button is type="submit" and then simply put a jQuery .click command in my javascript which calls the login function. So basically, just completely ignored the Angular way of doing it, which makes me a sad panda. :-\ Opera still doesn't work, but I don't care a ton about that I guess.
this is the code from Timothy E. Johansson's blog. I do not take credit.
app.directive("ngLoginSubmit", function(){
return {
restrict: "A",
scope: {
onSubmit: "=ngLoginSubmit"
},
link: function(scope, element, attrs) {
$(element)[0].onsubmit = function() {
$("#login-login").val($("#login", element).val());
$("#login-password").val($("#password", element).val());
scope.onSubmit(function() {
$("#login-form")[0].submit();
});
return false;
};
}
};
});
$scope.login = function(submit) {
$scope.user = {
login: $("#login").val(),
password: $("#password").val()
};
function ajaxCallback() {
submit();
}
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form name="login-form" id="login-form" method="post" action="" style="display: none;">
<input name="login" id="login-login" type="text">
<input name="password" id="login-password" type="password">
</form>
<form name="login-form" autocomplete="on" ng-login-submit="login">
<input id="login" name="login" type="text" autocomplete="on">
<input id="password" name="password" type="password" autocomplete="on">
</form>
The solution with AngularJS and without jQuery:
<form action="/" method="post" onsubmit="return false;">
<input type="text" name="username" autocomplete="on" id="email" ng-model="user.email">
<input type="password" id="password" name="password" autocomplete="on" ng-model="user.password">
<button type="submit" ng-click="login()">Submit</button>
</form>
Explantion
You should have action attribute in your form tag and a button with type=submit attribute. To prevent page from reloading, add onsubmit="return false;" to form tag. Simple :)
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.
}
});
Issue 1:
I'm trying to create a simple javascript function to check if all the characters entered into the field are numeric. The function is running, but not as I had hoped. I've located the isNaN function in javascript and it does not appear to be working. It enters the if statement every time, no matter if I type "asdf" or "1234" into the box.
Issue 2:
I want the form to stop submission obviously if the check for digits fails. However, I want it to continue to the submission page otherwise. I've been reading on ways to do this with pure JavaScript, and have the returns implemented as instructed. Is this a viable way to perform this? Alternatives?
Any help would be great on issue 1 or 2.
Here's my entire code:
<title>Bank System</title>
<script type="text/javascript">
function checkNumeric()
{
var pin = document.getElementById('pin');
if(isNaN(pin))
{
document.getElementById('message').innerHTML="Not A Valid Number";
return false;
}
else
{
return true;
}
}
</script>
<body style="background-color: gray;">
<h1>Welcome To Clayton's Credit Union</h1>
</br></br>
<form action="process.php" method="POST">
<label>Username: <input type="text" name="username"/></label>
</br>
<label>Pin Number<input type="text" maxlength="4" name="pin" id="pin"/></label>
</br></br>
<input type="submit" value="Submit" name="submit" onClick=" return checkNumeric()"/>
<p id="message"></p>
</br>
</form>
*Please note, I know this is not secure in anyway. I'm making this example specifically to show how vulnerable it is.
You are passing an element to isNaN rather than it's value. Try this:
var pin = document.getElementById('pin').value;
BTW
You should run this validation on the form submit rather than the button click:
<form action="process.php" method="POST" onsubmit="return checkNumeric()">
<input type="submit" value="Submit" name="submit" />
instead of:
<form action="process.php" method="POST">
<input type="submit" value="Submit" name="submit" onclick="return checkNumeric()" />
I'm using Google Checkout and having a problem with the onsubmit function.
I have an "Agree to terms" checkbox that I've put in place so that users must accept the terms before continuing with the checkout. I'm calling a function on the HTML form element...
function preCheckout() {
if( !document.getElementById('terms').checked ) {
// Requirements not accepted.
$('.warning').animate({top: -$('.warning').outerHeight()}, 500);
return false;
}
}
which contains the google checkout button like so:
<form method="POST"
action="https://sandbox.google.com..."
accept-charset="utf-8" onsubmit="preCheckout();">
<div>
<input type="checkbox" id="terms" name="accept_terms" value="" />
<p>I agree to all the terms and requirements...</p>
</div>
<input type="hidden" name="item_name_1" value="Simple Notes Monthly Subscription"/>
<input type="hidden" name="item_description_1" value=""/>
<input type="hidden" name="item_quantity_1" value="1"/>
<input type="hidden" name="item_price_1" value=""/>
<input type="hidden" name="item_currency_1" value="USD"/>
<input type="hidden" name="shopping-cart.merchant-private-data" value="" />
<input type="hidden" name="tax_rate" value="0.065"/>
<input type="hidden" name="tax_us_state" value="UT"/>
<input type="hidden" name="_charset_"/>
<input type="hidden" name="continue-shopping-url" value="/thankyou.php" />
<input type="image" name="Google Checkout" id="google-btn" alt="Fast checkout through Google"
src="https://checkout.google.com/buttons/checkout.gif?merchant_id=id&w=180&h=46&style=trans&variant=text&loc=en_US"
height="46" width="180"/>
</div>
</form>
However the page continues on with or without the checkbox being checked.
What am I missing?
FYI Here's the question I really meant to ask
When you right into the onsubmit line it's self, you return the true or false respectively, right? Like so:
onsubmit="return false;"
Well let's breakdown what is actually going in your code. Because you are potentially returning false in your code, here's the two possibilities of what might happen on submit.
onsubmit="false" // form is a success and performs form action
onsubmit="" // form is a success and performs form action
but what you're really looking for is onsubmit="return false;" or onsubmit="return true;" so here's what you need to do:
function preCheckout() {
if( !document.getElementById('terms').checked ) {
// Requirements not accepted.
$('.warning').animate({top: -$('.warning').outerHeight()}, 500);
return false;
}
// return true if everything is fine
return true;
}
However, the most important part is this:
<!-- all I did was add a "return" to your onsubmit -->
<form method="POST" action="https://sandbox.google.com..." accept-charset="utf-8" onsubmit="return preCheckout();">