Load whole page before javascript runs - javascript

I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}

You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>

You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.

Related

Form Validation - multiple inputs with same class

I am trying to validate inputs. On this particular page, I have 5 inputs. Three will be selected and all three require numbers. Just for this case, I am only going to check that the user has input a number (there will be more things to validate, but I want to get this right first so I don't repeat myself on multiple pages).
const formE = document.getElementById("SubmissionForm");
const sE = document.getElementById("input1");
const tE = document.getElementById("input2");
formE.addEventListener("click", validate);
function validate(e) {
e.preventDefault();
let valid = true;
if (!sE.value) {
const sError = document.querySelector("showError");
sError.forEach((showError));
sError.setAttribute("aria-hidden", false);
sError.setAttribute("aria-invalid", true);
}
return valid;
}
Now, I am aware this doesn't work with this (I got stuck thinking about a forEach and I just haven't taken it further yet.
In the HTML under the input I have this:
<span role="alert" class="showError" aria-hidden="true"> Please enter a number </span>
Bear in mind, this is just for the number validation I will add other validation points too.
So - what is the correct syntax for the JS to find all the showError classes and make their become visible when the user doesn't put in a number?
There are a lot of ways for that. Basically I can suggest this solution relevant to your question:
const button = document.querySelector('#button');
const number_1 = document.querySelector('#number_1');
const number_2 = document.querySelector('#number_2');
const error = document.querySelector('#error');
button.addEventListener('click',()=>{
if(isNaN(parseInt(number_1.value)) || isNaN(parseInt(number_2.value))){
error.removeAttribute('hidden');
}else{
error.setAttribute('hidden','');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validation Demo</title>
</head>
<body>
<input type="text" id="number_1">
<input type="text" id="number_2">
<button id="button">Check them!</button>
<p id="error" hidden>You can type only numbers!</p>
</body>
</html>

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Making a quiz in html/javascript alerts not working

Making a simple multiple choice, short answer and multiple response quiz on peanut butter and jelly :). What I'm trying to do is when the user clicks the "submit" button it shows the number of correct or incorrect answers. Also, next to the question show if the choice they chose was correct or incorrect, for example on the multiple choice question, if they select the right answer(jelly) then it would say "correct!" next to that option. Right now when I click submit nothing is happening, not sure why, I thought it would pop up an alert with the amount correct but nothing happens. I'm sure I'm missing something very simple but for some reason it hasn't popped out for me so any help will be greatly appreciated.
thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to make a proper Peanut Butter and Jelly
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src = "scripts/main.js"></script>
</head>
<body>
<header>
</header>
<main>
<form id = "quiz" name = "quiz">
<p>what item do you use to spread peanut butter on the bread?</p>
<input id = "textbox" type = "text" name = "question1">
<p>what is one ingrediant of peanut butter and jelly sandwich?</p>
<input type = "radio" id = "mc" name = "question2" value = "cheese"> cheese <br>
<input type = "radio" id = "mc" name = "question2" value = "bacon"> bacon <br>
<input type = "radio" id = "mc" name = "question2" value = "jelly"> jelly <br>
<p>which of the following are correct ingredients required to make a Peanut Butter and Jelly sandwich?</p>
<input type = "checkbox" id = "mc" name = "question2" value = "bread"> bread <br>
<input type = "checkbox" id = "mc" name = "question2" value = "cheese"> cheese <br>
<input type = "checkbox" id = "mc" name = "question2" value = "peanut butter"> peanut butter <br>
<input type = "checkbox" id = "mc" name = "question2" value = "jelly"> jelly <br>
<input type = "checkbox" id = "mc" name = "question2" value = "toothpaste"> toothpaste <br>
<br>
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check():">
<br>
</form>
</main>
<footer>
</footer>
</body>
javascript code
function src(){
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
var incorrect = 0;
if (question1 == "knife")
{
alert("correct!");
correct++;
}
else{
alert("incorrect");
incorrect++;
}
if(question2 == "jelly")
{
alert("correct!");
correct++;
}
else{
alert("incorrect");
incorrect++;
}
if(question3 == "bread"||"jelly"||"peanut butter"){
alert("correct!");
correct++
}
else{
alert("incorrect");
incorrect;
}
alert(correct);
}
To begin with, you seem like you are familiar with other programming languages. such as C# or java for example but you don't know the basics of DOM manipulation. So bear with me now till I explain it to you in brief details.
first of all, the DOM is the (Document Object Model) it is basically the image created using your mark up language (HTML). basically this is the things displayed on the browser and manipulated by javascript. like the buttons on this page or the text box I'm typing right now or the navigation bar above.
So, a quick recap the DOM is created using HTML and manipulated using javascript.
As the DOM is created by the html you won't be able to manipulate it until it till the html is loaded. you adding the script tag on the top of the html page means you run the manipulating things that are not there. So, you have to add the script tag at the end of the html page before the body closing tag.
<script src = "scripts/main.js"></script>
</body>
Now, when you want to manipulate an element you have to store it in a variable and the way to do this is by using a selector.
You have three options but just to save time I won't state the 3 I will state the best and most commonly used one. you can google the others but I don't think it is worth it though.
so if you know css you select a component wether by its name or id or class.
there is something in javascript called query selector and it is used like this.
var x = document.queryselector('css-selector');
Instead of the css-selector part you add a css selector.
for example if the element has a class of 'hero'. you will replace css-selector with .hero or if it has the id of 'hero' you will replace the css-selector with #id.
Then you should use the variable name to manipulate the element.
here are more useful links that you can check out.
JavaScript
Try removing the colon : on the submit button onclick
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check():">
Change this to
<input id = "button" type = "button" value = "Submit Quiz" onclick = "check()">
Right now, your submit onclick handler is check(). But you have no function called check(). Did you mean to do
onclick = "src()">
instead?
Do note that you should put all of your Javascript in the Javascript - it's bad practice to put handlers in the HTML, it'll only make things harder for you in the long run. Strongly consider using addEventListener.

Creating a quiz page using Javascript

I was trying to create a simple quiz page using Javascript. Else it went well, but after I run this code in browser, on pressing submit button the DOM text appeared in paragraph(through Script) disappears just after a flash. I had expected the text to remain on screen until the next action. Please help me troubleshoot this problem.
Thank you
Code
<!DOCTYPE HTML>
<html>
<head>
<title>
Quiz
</title>
<script type = "text/Javascript">
function checkAnswers()
{
var myQuiz = document.getElementById( "myQuiz" );
if ( myQuiz.elements[ 2 ].checked )
document.getElementById("demo").innerHTML = "Congrats, Thats the Right answer";
else
document.getElementById("demo").innerHTML = "Woops!! The Correct answer is 'Mouse'.<br>Click 'Next' to Proceed";
}
</script>
</head>
<body>
<br><br><br><br><br><br>
<form id = "myQuiz" onsubmit = "checkAnswers()" action = "">
Which among the following is readily found in computers ?
<br><br><br>
<input type = "radio" name = "radiobutton" value = "A" /><label> Zebra</label>
<input type = "radio" name = "radiobutton" value = "B" /><label> Girrafe</label>
<br><br> <input type = "radio" name = "radiobutton" value = "C" /><label>Mouse</label>
<input type = "radio" name = "radiobutton" value = "D" /><label>Mosquito</label>
</div><br><input type = "submit" name = "submit" value = "Submit" />
<br>
<p id = "demo" "> </p>
</form>
</body>
</html>
Make the following changes:
HTML
<form id = "myQuiz" onsubmit = "checkAnswers(event)" action = "">
JS
function checkAnswers(event) {
event.preventDefault();
...
}
preventDefault cancels the form submit event which is causing the page to reload and your text to disappear.
DEMO
Just return "false" inside the onSubmit parameter, like this:
<form id = "myQuiz" onsubmit = "return false" action = "">
And invoke the checkAnswers() function when someone clicks the button;
<input type = "submit" name = "submit" value = "Submit" onclick="checkAnswers()" />

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)

Categories