How to call multiple functions with DOM and Javascript - javascript

I'm working on an assignment and need to validate multiple inputs. I have created multiple functions and am having trouble calling each one. The first one is the only one that will call. The other two will just hang and do nothing.
If I do a single function call for oninput at the form tag it works. Just that it automatically calls the function and all validations. This causes all the prompts to come out at the same time which I don't want. This is why the oninput call is being done at the input tag.
HTML:
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"
oninput="nameValidation()"/> <br />
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"
oninput="emailValidation()"/> <br />
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID"
oninput="phoneValidation()"/>
Javascript
function nameValidation() {
var name = document.getElementById("nameID").value;
if (name.length < 3) {
document.getElementById("nameValidate").innerText = "Please
enter your full name.";
}
else if (name.length > 3) {
document.getElementById("nameValidate").innerText = "";
}
}
function emailValidation() {
var email = document.getElementById("emailID").value;
if (!email.match(".com") && email < 5) {
document.getElementById("emailValidate").innerText = "Please
enter your full email address.";
}
else {
document.getElementById("emailValidate").innerText = "";
}
}
function phoneValidation() {
var phone = document.getelementbyid("phoneID").value;
if (phone == "" || phone.length < 10) {
document.getelementbyid("phoneValidate").innertext = "please
enter your full phone number.";
}
else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
}

Let's back up a minute and break some very bad habits that someone who doesn't know any better is teaching you.
Do not set up events using inline HTML event attributes (ie. onclick). This is a 25+ year old technique that persists today because people just copy/paste it and it seems to work in many cases. However, there are a number of very good reasons not to use this ancient technique that just will not die. Separate your JavaScript from your HTML and use modern, standards-based approaches to event handling with .addEventListener().
You've also mis-capitalized .getElementById() when you were getting the phone data and this would cause an error in your code that would prevent it from continuing. Always work with your developer tools (F12) open and the Console tab showing as this is where error messages will appear.
Next, only query the DOM once for elements that you'll need over and over. This means remove all the document.getElementById() lines from inside the functions and move them so they just get executed only once.
And, don't make references to properties of DOM elements, make the references to the element itself. This way, you scan the document just once to get the element reference, but then you can get any property you like when you need it without having to scan the document for the same element again.
Next, don't use .innerText as it is non-standard. Use .textContent instead.
And, don't use self-terminating tag syntax (ie.<br />, <input />). Here's why.
So, here's what your code should look like:
// Get references to the elements you'll be working with just once
var userName = document.getElementById("nameID");
var nameValidate = document.getElementById("nameValidate");
var email = document.getElementById("emailID");
var emailValidate = document.getElementById("emailValidate");
var phone = document.getElementById("phoneID");
var phoneValidate = document.getElementById("phoneValidate");
// Set up your event handlers in JavaScript, not HTML
userName.addEventListener("input", nameValidation);
email.addEventListener("input", emailValidation);
phone.addEventListener("input", phoneValidation);
function nameValidation() {
if (this.value.length < 3) {
nameValidate.textContent = "Please enter your full name.";
} else {
nameValidate.textContent = "";
}
}
function emailValidation() {
// Check the last 4 characters of the input
if ((this.value.substr(this.value.length - 4) !== ".com") && email.value.length < 5) {
emailValidate.textContent = "Please enter your full email address.";
} else {
emailValidate.textContent = "";
}
}
function phoneValidation() {
if (phone.value == "" || phone.value.length < 10) {
phoneValidate.textContent = "please enter your full phone number.";
} else {
phoneValidate.textContent = "";
}
}
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"> <br>
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"> <br>
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID">
Finally, as a professional technology trainer for over 25+ years, I would strongly advise you to inform whoever is teaching you these outdated techniques that they are doing you and anyone else they are teaching a disservice. Modern web development is hard-enough without having to unlearn bad habits brought on by those who don't know any better.

Firstly, your elseif has brackets but the condition is empty. Check your console, it should be showing a syntax error because:
} else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
is not valid syntax. Turn it into an else.
Secondly, the function:
document.getelementbyid("phoneValidate").innertext = "";
does not exist on document, however, getElementById does.
Finally, ensure that you use the console to help you debug your code.

Related

The form does not work correctly when sent

I wrote the code for a form validation.
Should work like this:
It checks (allLetter (uName)) and if it's true, then validate the next input.
If any validation is false then it should return false.
My problem is that if both validations are true, then everything is exactly false and the form is not sent.
If I set true in formValidation (), if at least one check false, the form should not be sent.
<form name='registration' method="POST" onSubmit="return formValidation();">
<label for="userName">Name:</label>
<input type="text" name="userName" size="20" />
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" size="20" />
<input type="submit" name="submit" value="Submit" />
</form>
function formValidation() {
var uName = document.registration.userName;
var uPhone = document.registration.userPhone;
if(allLetter(uName)) {
if(phone(uPhone)) {}
}
return false;
}
function phone(uPhone){
var digts = /^[0-9]+$/;
if(uPhone.value.match(digts)){
return true;
} else {
alert('Phone must have only digits');
uPhone.focus();
return false;
}
}
function allLetter(uName) {
var letters = /^[A-Za-z]+$/;
if(uName.value.match(letters)) {
return true;
}else{
alert('Username must have alphabet characters only');
uName.focus();
return false;
}
}
First, you are using a 20+ year old way to gain references to your elements (document.form.formElementNameAttributeValue) and, while this still works for legacy reasons, it doesn't follow the standard Document Object Model (DOM) API.
Next, you've broken up your validation tests into different methods (and that's certainly not a bad idea for reusability), but in this case is is adding a ton of code that you just don't need. I've always found it's best to start simple and get the code working, then refactor it.
You're also not using the <label> elements correctly.
One other point, your form is set to send its data via a POST request. POST should only be used when you are changing the state of the server (i.e. you are adding, editing or deleting some data on the server). If that's what your form does, you'r fine. But, if not, you should be using a GET request.
Lastly, you are also using a 20+ year old technique for setting up event handlers using inline HTML event attributes (onsubmit), which should no longer be used for many reasons. Additionally, when using this technique, you have to use return false from your validation function and then return in front of the validation function name in the attribute to cancel the event instead of just using event.preventDefault().
So, here is a modern, standards-based approach to your validation:
// Get references to the elements you'll be working with using the DOM API
var frm = document.querySelector("form[name='registration']");
var user = document.getElementById("userName");
var phone = document.getElementById("userPhone");
// Set up event handlers in JavaScript, not with HTML attributes
frm.addEventListener("submit", formValidation);
// Validation function will automatically be passed a reference
// the to event it's associated with (the submit event in this case).
// As you can see, the function is prepared to recieve that argument
// with the "event" parameter.
function formValidation(event) {
var letters = /^[A-Za-z]+$/;
var digts = /^[0-9]+$/;
// This will not only be used to show any errors, but we'll also use
// it to know if there were any errors.
var errorMessage = "";
// Validate the user name
if(user.value.match(letters)) {
// We've already validated the user name, so all we need to
// know now is if the phone is NOT valid. By prepending a !
// to the test, we reverse the logic and are now testing to
// see if the phone does NOT match the regular expression
if(!phone.value.match(digts)) {
// Invalid phone number
errorMessage = "Phone must have only digits";
phone.focus();
}
} else {
// Invalid user name
errorMessage = "Username must have alphabet characters only";
user.focus();
}
// If there is an error message, we've got a validation issue
if(errorMessage !== ""){
alert(errorMessage);
event.preventDefault(); // Stop the form submission
}
}
<!-- 20 is the default size for input elements, but if you do
want to change it do it via CSS, not HTML attributes -->
<form name='registration' method="POST">
<!-- The for attribute of a label must be equal to the id
attribute of some other element, not the name attribute -->
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" id="userPhone">
<input type="submit" name="submit" value="Submit">
</form>

How to do custom validation in JavaScript

I have a function that currently works with an input to prevent customers from inputting a P.O. Box into an address field. The input that works has an inline onKeyPress event, however the input I need to run the function on doesn't (and I can't access it).
My question is how to incorporate the correct event listener so that my function runs on this inaccessible input?
My JS Fiddle is here: http://jsfiddle.net/ZQQS9/4/
function killPObox(id) {
var idValue = document.getElementById('v65-onepage-shipaddr1').value;
if (id == 'v65-onepage-shipaddr1') {
function runVal() {
if (idValue.substr(0,4).toUpperCase() === "PO B" || idValue.substr(0,5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
setInterval(runVal(),1);
}
}
<!-- Practice input that works -->
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" onKeyPress="killPObox(this.name)">
<br>
<br>
<!-- Actual input that I need to hook into, cannot edit -->
2. <input type="text" size="25" maxlength="75" name="ShipAddress1" id="v65-onepage-shipaddr1" value="" style="" onkeydown="">
You can use the addEventListener() method like this:
document.getElementById('v65-onepage-shipaddr2').addEventListener('keypress', killPObox('v65-onepage-shipaddr2'));
I think your first input is incorrectly passing this.name as the argument to the killPObox() function. Should you be passing this.id instead? Also you may want to replace 'v65-onepage-shipaddr1' in your killPObox() function to just id to use the argument passed into the function.
I'm sure you have solved this already, but since this is still unanswered (and I stumbled on it) I'll add the solution for future visitors.
Use the correct event
First off, the onKeyPress will actually fire before the typed character has been registered in the input element. So if a user types abc and you do onKeyPress="alert(this.value)" it would alert ab. A better alternative would be onKeyUp, since this would get the last typed character too.
Use the event correctly
Next, the events - your options are:
//inline, not considered "best practice"
<input type="text" name="myinput" id="myinput" onKeyUp="killPObox(this)"/>
//same event as above, but in pure js
document.getElementById('myinput').onkeyup = function (e) {
killPObox(e.target);
};
//or attach an eventListener
document.getElementById('myinput').addEventListener('keyup', function (e) {
killPObox(e.target)
});
All of these should work for the majority of browsers. I would suggest alternative 3, or if you need IE8 support, alternative 2.
The JavaScript, simplified
Your function, killPObox(), should look something like this (using one of the above events):
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
Last but not least..
Finally, a very important part when using event binding, you need to use window.onload(). This is to make sure that both the script and elements that are to be bound are loaded before any code is run.
window.onload = function () {
// my binds, events and calls here
};
An actual working example of all three events:
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr0' || el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
window.onload = function () {
document.getElementById('v65-onepage-shipaddr1').onkeyup = function (e) {
killPObox(e.target);
};
document.getElementById('v65-onepage-shipaddr2').addEventListener('keyup', function (e) {
killPObox(e.target)
});
};
"PO B" or "P.O. " will trigger the alert in all boxes:<br><br>
0. <input type="text" class="quantity" name="v65-onepage-shipaddr0" id="v65-onepage-shipaddr0" onKeyUp="killPObox(this)" />
<br/><br/>
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" />
<br/><br/>
2. <input type="text" class="quantity" name="v65-onepage-shipaddr2" id="v65-onepage-shipaddr2" />

changing class with onkeypress

I'm learning javascript and i'm using bootstrap so i don't really have to worry about css.
I have a form group and i want to add class as the user inputs something. Here's my code:
<div class="form-group" id="loginForm">
<label for="inputLogin" class="pull-left">Login</label>
<input type="text" class="form-control" id="inputLogin" placeholder="Enter login" onkeypress="changeToGreenBorder('loginForm','inputLogin')">
</div>
and it's calling those functions:
function changeToGreenBorder(string,string2){
var tag = getElement(string);
var tag2 = getElement(string2);
if (tag2.innerHTML.length > 6) {
tag.setAttribute('class','form-group has-success');
} else if({
tag.setAttribute('class','form-group has-error');
}
}
function getElement(string){
var doc = document;
return doc.getElementById(string);
}
It's working with the error class, but when it has more then 6 letters, it doesn't switch to success class. How can i solve this?
You had a lingering ( and a Else If without a condition so I'm thinking you don't need a Else If
You were also trying to get the lenght of the innerHTML when what you really wanted was the lengthof the elements' value;
Working JSFiddle

javascript alerts refuse to work in form validation?

i keep trying everything to get these alerts to pop up correctly. i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. here is the entire code that doesnt do anything:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- VARIABLE DECLARATION -->
f1.city.focus();
function check_form()
{
at_sign = email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
}
else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
}
else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
}
else if((at_sign<1) || (email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" action="smartform.html">
<b>City</b>
<input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
<b>State</b>
<input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
</form>
</BODY>
</HTML>
edit: nothing seems to be working that everyone says.. here is my new code:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
f1.city.focus();
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
if(f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
return false;
}
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
return false;
}
else if((at_sign<1) || (f1.email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
return false;
}
else
{
//document.write("Form completed");
}
return false;
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" onSubmit="return check_form(this)">
<b>City</b>
<input type = "text" name = "city" size = "18" value="">
<b>State</b>
<input type = "text" name = "state" size = "4" value="">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="">
<input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
</form>
<b>hi</b>
</BODY>
</HTML>
still get no alerts... i put that hi up and got that.. but no alerts......
alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. I simplified it to this:
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function check_form()
{
document.write("Form started");
var at_sign = document.f1.email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
document.f1.city.focus();
//return false;
}
else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
document.f1.state.focus();
//return false;
}
else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
{
alert('Please enter a 5 digit zip code');
document.f1.zip.focus();
//return false;
}
else if((at_sign<1) || (document.f1.email.value.length<3))
{
alert('Please enter a valid email address');
document.f1.email.focus();
//return false;
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY onLoad= "javascript:document.f1.city.focus();">
<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
<b>City</b>
<input type = "text" name = "city" size = "18">
<b>State</b>
<input type = "text" name = "state" size = "4">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5">
<b>Email</b>
<input type = "text" name = "email" size = "18">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>
</BODY>
</HTML>
I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. but my question is, why doesnt an alert happen along the way to this result? it seems like even if the page got overwritten, it should still pop up. also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement?
update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error?
also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? I'm attempting this as i type.
You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, e.g.
<form onsubmit="return check_form(this);" ...>
You should reference the controls as properties of form using their name, don't use the name as a global variable. And declare all variables.
So the function looks like:
function check_form(form) {
var at_sign = email.search(/#/);
if (form.city.value.length < 1) {
alert('Please enter a city');
f1.city.focus();
// cancel submit by returning false
return false;
} else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
...
}
You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt.
Using document.write after the page has finished loading (e.g. when submitting the form) will erase the entire content of the page before writing the new content.
Edit
Here's what's wrong with your new code:
<SCRIPT LANGUAGE="JavaScript">
Get rid of the language attribute. It's not harmful (well, in a very specific case it might be).
f1.city.focus();
f1 has no been defined or initialised (see comments above about element names and global variables)
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
f1.email is an input element, it has no search property, you can't call it. It does have a value property that is a string, perhaps you meant:
var at_sign = f1.email.value.search(/#/);
Then there is:
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. You want:
else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))
Note that this requires users to enter the state in capital letters, it might help to tell them about that.
Then there is:
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))
isNaN is a global variable, not a method of strings. If no value has been entered, then the value is the empty string and isNaN('') returns false. If you want to test that 5 digits have been entered then use:
else if (!/^\d{5}$/test(f1.zip.value))
There is no need to test against true, just use it, nor is there a need to group simple expressions:
else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))
Then finally, if all the test pass:
return false;
that stops the form from submitting. You can omit this return statement, returning undefined will let the form submit. Or return true if you really want.
Ok I want to answer your question but first things first lets walk through your
code and clean it up.
Use this as a template of properly formated code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Form</title>
</head>
<body>
<!-- Code goes here -->
<script type="text/javascript">
</script>
</body>
</html>
Tags & attributes don't need to be capitalized. Javascript comments are like this:
/** Comment. */
Html comments are like this:
<!-- Comment. -->
Also nitpick: attributes should be followed by an equal sign not a space. i.e.
<form name="f1" id="smartForm" action="smartform.html"> ... </form>
Next up proper event binding.
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. Open up the developer console. Evergreen browsers (Chrome, Firefox etc...) have good ones these day. The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. So look up how to open up the developer console in your browser for your platform and type this into your console:
1+1
Should evaluate to: 2.
Next type: document
If you click around you can see that you can walk through the dom a little bit.
Next load up your smartForm app with my changes above and type:
document.getElementById('smartForm')
You should see your element. This is how to properly query objects in the dom.
You'll notice that if you type document.smartForm doesn't work. You should get null, this should tell you that there should be a way to get the element from the document. Hint, it's getElementById. So if you put id's on all your inputs then you can make a list of all the document objects you can query:
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
Next you can start querying the values and such like you were doing:
cityElement.value.length != 2
A cleaned up version would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Smart form</title>
</head>
<body>
<form id='smartForm' action='smartform.html'>
<b>City</b>
<input type="text" id="city" size="18">
<b>State</b>
<input type="text" id="state" size="4">
<b>Zip Code</b>
<input type="text" id="zip" size="5">
<b>Email</b>
<input type="text" id="email" size="18">
<input type="submit" value="done">
</form>
<script type="text/javascript">
var validateForm = function(evt) {
var error = false;
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
if (cityElement.value.length != 2 ||
!(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
error = true;
alert('oops');
cityElement.focus();
}
// etc..
if (error) {
evt.preventDefault();
}
};
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
</script>
</body>
</html>
Ok a couple more things I noticed. charCodeAt is for strings only. "hi".chatCodeAt not element.charCodeAt. Also you have this random variable at_sign.
You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console
Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. Trust me, let debugging tutorials be your bread at butter!
Full working example of your code:
http://codepen.io/JAStanton/pen/tjFHn?editors=101
A little less verbose version:
http://codepen.io/JAStanton/pen/iBJAk?editors=101
onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p
<form onsubmit="return check_form();" ...
There are several mishaps in your code that might also cause errors and prevent that from working
Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen)

Javascript form validation only works in firefox

I am relatively new to Javascript so I'm hoping this is a simple mistake. I building a generic form validation function that is called on the form's onSubmit. The function loops through all the form's child elements, looks for certain classes, and analyzes the contents of the appropriate fields. If it finds something missing or erroneous, it displays the appropriate error message div and returns false, thus preventing the form from being submitted to the php page.
It works well in firefox 3.6.3, but in every other browser I've tested (Safari 4.0.4, Chrome 4.1, IE8) it seems to ignore the onSubmit and jump straight to the php processing page.
HTML CODE:
<form name='myForm' id='myForm' action='process_form.php' method='post' onSubmit="return validateRequired('myForm')">
<fieldset class="required radioset">
<label for='selection1'>
<input type='radio' name='selection' id='selection1' value='1'/>
Option 1
</label>
<label for='selection2'>
<input type='radio' name='selection' id='selection2' value='2'/>
Option 2
</label>
<label for='selection3'>
<input type='radio' name='selection' id='selection3' value='3'/>
Option 3
</label>
<label for='selection4'>
<input type='radio' name='selection' id='selection4' value='4'/>
Option 4
</label>
<div class='errorBox' style='visibility:hidden'>
Please make a selection
</div>
</fieldset>
<fieldset class="required checkset">
<label>
Choice 1
<input type='checkbox' name='choices' id='choice1' value='1'/>
</label>
<label>
Choice 2
<input type='checkbox' name='choices' id='choice2' value='2'/>
</label>
<label>
Choice 3
<input type='checkbox' name='choices' id='choice3' value='3'/>
</label>
<label>
Choice 4
<input type='checkbox' name='choices' id='choice4' value='4'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please choose at least one
</div>
</fieldset>
<fieldset class="required textfield" >
<label for='textinput1'>
Required Text:
<input type='text' name='textinput1' id='textinput1' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please enter some text
</div>
</fieldset>
<fieldset class="required email textfield">
<label for='email'>
Required Email:
<input type='text' name='email' id='email' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
The email address you have entered is invalid
</div>
</fieldset>
<div>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
</div>
</form>
JAVASCRIPT CODE:
function validateRequired(id){
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
/*RADIO BUTTON or CHECK BOX SET*/
if(hasClass(elem,"radioset") || hasClass(elem,"checkset")){
var inputs = elem.getElementsByTagName("input");
var check = false;
for(j = 0; j < inputs.length; j++){
if(inputs[j].checked){
check = true;
}
}
if(check == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
/*TEXT FIELD*/
else if(hasClass(elem,"textfield")){
var input = elem.getElementsByTagName("input");
if(input[0].value == ""){
errors += 1;
showError(elem);
} else {
hideError(elem);
/*EMAIL ADDRESS*/
if(hasClass(elem,"email")){
if(isValidEmail(input[0].value) == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
}
}
}
}
if(errors > 0){
returnVal = false;
} else {
returnVal = true;
}
return returnVal;}
I know this is a lot of code to look at, but any help would be appreciated. Since it works fine in one browser, Im not sure how to start debugging.
Thanks
Andrew
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
The problem is that your required and other classes are put on the <fieldset> element.
Fieldset elements are included in the form.elements collection on IE, Firefox and Opera, but not WebKit browsers (Chrome, Safari). It is these browsers where your form fails for me.
It has always been a weird quirk that <fieldset> was included in the elements collection. The DOM Level 2 HTML spec states that only ‘form control elements’ should be present in the collection, and by HTML4's definition that would seem not to include fieldsets, which have no control name or value.
You could perhaps change your code to use getElementsByTagName to pick up the fieldsets instead:
var fieldsets= form.getElementsByTagName('fieldset');
for (var i= 0; i<fieldsets.length; i++) {
var elem= fieldsets[i];
I would not use hasClass. Here's another way to try that might work better for you:
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
// do something here with a <input type="text" .../>
alert(node.value);
}
}
I know that IE has problems getting the classes from some elements which have multiple classes associated with them. Regardless, this is a handy function.
If you have any kind of JavaScript error, the function will not return false, and therefore the default behavior of submitting the data will be triggered.
Try running your code through [http://www.javascriptlint.com/online_lint.php][1] first, then a debugger.
try not to use if(errors > 0)...just in every condition (for wrong input) put return false;
and at the end before the last bracket put return true;
and better use:
onSubmit="return validateRequired(this)"
and there is no need in this lines (in case you remove the errors var)
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
Not the cause of your problem, I'm sure, but it's best not to serve a set of radio buttons without one of them selected.
In your particular case, if you know that you set one when you serve the page, you don't need a "required" check; there's no way the user can get the radio buttons into a state where none are selected. Pick a sensible default, make it the first option, and make it selected. Simplify your life :)
From the W3C:
http://www.w3.org/TR/html401/interact/forms.html#radio
If no radio button in a set sharing
the same control name is initially
"on", user agent behavior for choosing
which control is initially "on" is
undefined. Note. Since existing
implementations handle this case
differently, the current specification
differs from RFC 1866 ([RFC1866]
section 8.1.2.4), which states:
At all times, exactly one of the radio
buttons in a set is checked. If
none of the <INPUT> elements of a set
of radio buttons specifies `CHECKED',
then the user agent must check the
first radio button of the set
initially.
Since user agent behavior differs,
authors should ensure that in each set
of radio buttons that one is initially
"on".
Back to basics for a second: You say it "seems to ignore the onsubmit". That leaves three possibilities that I can think of:
Your function is never called
It's called, and is bombing out part-way through due to an error
It's called, and isn't doing what you think it is, always returning true
It's not clear from your question which it is, so if I were you I'd start debugging this by putting an alert at the beginning of the function to see whether IE's calling it at all - then move that alert down and run the validation again, and see where it stops appearing (any error must be above that point).
I'd also want to alert the return value from the place it was called, to see what was coming back. If it's always true, then your code is working but not doing what you think it does.
From there, you at least have a clearer grasp of what's going on, if not an exact block of code to be scrutinising.

Categories