javascript alerts refuse to work in form validation? - javascript

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)

Related

How do I display an error message if the input is wrong on HTML

Im trying to display an error message in RED beside the input field to let the user know, however I dont know why my error message is not working. The requirement for the input is starting with a capital letter, followed by non special characters (any alphabets) please help me see what is wrong with my code
I am still new to HTML and I know many people said about regex but im not sure i have not learn that
<html>
<script>
function validateForm() {
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
</script>
<style>
#errorName
{
color:red;
}
</style>
<form action="handleServer.php" method="get" onSubmit="return validateForm()">
<body>
<!-- starting with first name-->
First name: </br>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName"></br>
<input type="submit" value="Submit">
</body>
</form>
</html>
I see your if statements are not closed properly and also the input box.
Please find codepan
function validateForm() {
console.log(1);
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
}
}
When i tend to use regex i store it in its own value like this:
const patternName = /[0-9]|[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/|#]/;
let resultName = patternName.test(name.value);
The code above checks if the name contains anything from the regex above and if it does resultName will return true.
Next we can do the following:
If name is empty you get an error and it contains anything from the regex above we. In this case we show the error
If resultName is true we know that name contains something from the regex, so that it's not a valid name.
If not we show success message
if (name.value === "" || resultName) {
showErrorName();
} else {
showSuccessName();
}`

Beginning Javascript form validation

this is my first time posting.
I'm in a beginner Javascript class with the following assignment:
"Students are required to enter into a text box their course information in the following format:
AAA.111#2222_aa-1234
Your Web page will ask the user to type their information in a text box. The user will then click a form button named validate. If the format is correct a message will be generated below the button that reads "Correct Format". If the format is incorrect a message will be generated that reads "Incorrect Format". "
After my first attempt, I got the following feedback:
"You do not need a form for this assignment .You only need a text box and a button. Place your function on your button (onClick event). You only need one function for this assignment.  Your function should include getting the users input from the text box. You can use getElementById() and .value it should also include the regular expression, and what to so if it is correct or wrong."
So far I have the following:
function isValid(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return (myRegExp.test(text);
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src = "registerFourth.js"></script>
</body>
</html>
So sorry if I am not posting this correctly. My code is telling me I have a "Parsing Error: Unexpected Token" and when I fill in the text box and click Validate nothing happens. Thank you!
There are multiple issues in your approach.
1. Your isValid method expects text parameter which is not required
2. Your isValid method is recursive, I don't see why that is needed.
Please check below if it works for you.
function isValid() {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
var text = document.getElementById("course").value;
var match = myRegExp.test(text);
if(match) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format";
}
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
You had a few syntax errors:
return (myRegExp.test(text); should be return myRegExp.test(text);
isValid(document.getElementById("course".value) should be isValid(document.getElementById("course").value)
And finally, putting the return statemenet before the rest of your code defeats the whole purpose of the rest of your code. return breaks out of your current function, which means the if else statement is rendered useless.
function isValid(text) {
var myRegExp = "/([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/";
return myRegExp.test(text);
if (isValid(document.getElementById("course").value)) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type="text" name="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src="registerFourth.js"></script>
</body>
</html>
There are a couple of syntax as well as function construction issues with this.
You have a missing ) in 2 lines -
return (myRegExp.test(text);
and
if (isValid(document.getElementById("course".value) line
You are also returning the value before the conditional statement. So the block below, will never run. Returning a function value ends the function execution
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
Think about functions in terms of inputs and outputs and what function it performs.
For example,
/// this function only takes a string and tests if it matches the regex
/// input: string
/// output: true / false (boolean)
function testRegex(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return myRegExp.test(text)
}
/// this function runs when the button is clicked, calls the testRegex fn
/// and handles setting the output element
/// note: read about ternary conditional operators if confused about ?:
function isValid() {
const outputEL = document.getElementById("output")
const courseEl = document.getElementById("course")
outputEl.innerHTML = testRegex(courseEl.value) ? "Correct Format" : "Incorrect Format";
}
If you want to understand how the code is being executed -
the script tags loads your registerFourth.js which will contain the two functions I defined above - isValid and testRegex. Note that the functions are just defined and not executed yet
when you click the button, the isValid function starts executing
the isValid function gets the output element and course element
isValid then calls testRegex with the value of course element
now, testRegex runs with the value provided to it and returns (to the calling function, isValid is this case) a boolean value, based on if the value is valid
isValid is back in power and depending on the value testRegex sent it, it sets outputEl to CorrectFormat / Incorrect Format
isValid ends!
You miss a few closed brackets.
See updated RegExp .
Change document.getElementById("course".value) to document.getElementById("course").value
You use of return incorrectly, in my code no need return .
see full code :
function isValid() {
var text = document.getElementById("course").value;
var myRegExp = /^([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa|aa)-\d{4}$/;
document.getElementById("output").innerHTML = myRegExp.test(text) ? "Correct Format" : "Incorrect Format" ;
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
this line is invalid
return (myRegExp.test(text);
If you want to return if the test is true
if (myRegExp.test(text)) return;
You also need to close the () here with 2 more )
if (isValid(document.getElementById("course").value))
That should solve your syntax issues. Not your logic though...

JavaScript - Faulty logic in simple data validation

I am super new to coding and having a difficult time with some of the logic. I asked another question last night and the community was really helpful (Thanks!), so I thought I'd try it again. `
I am trying to make an program that collects the user's email and first name. I want to check that there is something entered in each of the boxes on the form and, in order to ensure they entered their email address correctly, that emailAddress1 is the same as emailAddress2.
I have defined a "var errorMessage = "";" and if there is error at any point, it redefines a new errorMessage based on the mistake the user made on the form.
The problem, I think is with the second if-else statement. I thought that if the "errorMessage = "";" still, it would submit the form. However, no matter what it's executing the else statement and I'm getting an alert of an empty error message.
Why, if errorMessage = "", is it running the else statement and skipping over the if statement that uses errorMessage = "" as the condition?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress2 = $("email_address2").value;
var firstName = $("first_name").value;
var errorMessage = "";
// validate the entries
if (emailAddress1 == "") {
errorMessage = "First email address entry required";
$("email_address1").focus();
} else if (emailAddress2 == "") {
errorMessage = "Second email address entry required";
$("email_address2").focus();
} else if (emailAddress2 != emailAddress1) {
errorMessage = "Email address entries must match";
$("email_address2").focus();
} else if (firstName == "") {
errorMessage = "First name entry required";
$("first_name").focus();
}
// submit the form if all entries are valid
// otherwise, display an error message
if (errorMessage = "") {
$("email_form").submit();
} else {
alert(errorMessage);
}
};
window.onload = function() {
$("join_list").onclick = joinList;
$("email_address1").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Join Email List</title>
<link rel="stylesheet" href="email_list.css">
<script src="email_list.js"></script>
</head>
<body>
<main>
<h1>Please join our email list</h1>
<form id="email_form" name="email_form" action="join.html" method="get">
<label for="email_address1">Email Address:</label>
<input type="text" id="email_address1" name="email_address1"><br>
<label for="email_address2">Re-enter Email Address:</label>
<input type="text" id="email_address2" name="email_address2"><br>
<label for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name"><br>
<label> </label>
<input type="button" id="join_list" value="Join our List">
</form>
</main>
</body>
</html>
**
So you have a typo in your code where you are not comparing, you are setting the variable equal to an empty string. And an empty string is a falsy value
So your code is basically this
errorMessage = "";
if (errorMessage) {
} else {
}
Using a tool like jshint, jslint, eslint, etc build into your IDE will help you catch these typos. So alter your code to do the correct comparison.
if (errorMessage === "") {
I'm not sure if you can extract values form inputs this way.
email_address1 is element id so you must refer to it with hashtag on the beginning.
Proper way in jQuery to do this $("#email_address1").val()
Difference between =, == and === is quite important.
let testVariable = 123; // only assigns value to a variable
Difference between = and == is quite obvious. Between == and === is little bit more complicated.
== operator compares only values and does not recognize data types but === recognizes them. What it means to to you?
Lets say than you have variable testNumber with assigned value 123 as a number and variable textText with assigned value "123"(notice the quotes).
If you compare them with == expression returns true but if you compare them with === expression returns false.
let testNumber = 123;
let testText = "123";
As you can see variable testText is in doublequotes which means it's datatype is String. String is just normal text. But testNumber variable has datatype Integer. Integer is just normal number. Content of these two variables does not differ but datatypes does.
testNumber == testText //true - same content, different datatype we ignore that
testNumber === testTExt // false - same content, different datatype but now we consider it
I hope I helped you at least a little bit. :)
Edit: Also i suggest you to open developer tools(F12) in chrome and check console. You can see errors in there. It helps you a lot.

Javascript can't locate HTML form ID

I'm creating a basic HTML form, and a Javascript form validator that looks for any input value in the "first name" field. The problem I'm having is that nothing seems to be working to return the first name form value to check it in JS.
Relevant HTML:
<form id="form1" name="formName">
First name:<br>
<input type="text" id="fn" >
<br>
Last name:<br>
<input type="text" name="ln" >
<br>
Email address: <span style="color:red">(required)</span><br>
<input type="text" name="email" >
<br><br>
<button onclick="validate()">Submit</button>
</form>
My JS:
var validate = function (){
var x = document.getElementById("fn").value;
if (x == null || "" || "undefined"){
alert("Please fill out your first name");
return false;
}
kickoff();
}
var kickoff = function () {
var visitor = document.forms["form1"].fn.value;
alert("Thanks for filling out, " + visitor +"\n");
return visitor;
};
Here's a JSFiddle.
My X variable is never reached, it seems, and keeps returning "undefined" when I submit the page. I've been fiddling with it for quite a while and can't seem to figure out what I'm doing wrong. Any help?
This doesn't mean what you think:
if (x == null || "" || "undefined") {
Can also be written as:
if ((x == null) || // might be false
"" || // will be false
"undefined" // will be true
) {
so the if will always be true.
You really just need:
if (! x) {
Besides the syntax issues, that method is also out-of-scope. You're not even going to be able to debug the issue with your conditional until you fix that.
You can either in-line the script higher up in the DOM or define validate directly on the window object:
window.validate = function () {
http://jsfiddle.net/frg37t3u/5/
Neither case is ideal, you should know. Globals are bad, but that's another discussion.

form validation javascript stop new window from opening

I have written a large page including a form as my first JavaScript project. I've gotten some help here, so thanks. I am very happy with what I have so far, but I have one last problem I need to deal with.
The code I will submit here is a tester. I have a couple of functions attached to an onClick new window. What happens is user submits form and their info appears in a new window. (My original page is more complicated, of course.) There is one function called askForHelp which shows an alert in the new window if a specific value is entered for 'state' and a very simple validateForm which shows an alert on the parent?? window if values are left blank.
The problem is b/c i have all the functions running onClick, and I realize they run concurrently, the new window opens no matter what the user does (with the alerts showing in their various places).
Based on other similar questions here, I tried adding a return false and return true statements to my conditionals, but this hasn't done anything.
Now I know there are much better ways to do what I am doing here, and that my form validation is basic and weak, but as my first foray into programming, it was very important for me to understand everything I am doing, which I do, as of now.
Can anyone show me how to fix this so the new window only opens if the form validates? I would prefer no jquery or no radical chances to the code, if possible.
I appreciate everyone's input. Here is the code:
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if ((volunteer == "New York") || (volunteer == "NY") || (volunteer == "New Jersey") || (volunteer == "NJ")) {
allInfo.alert("test test test");
return false;
}
else {
return true;
}
}
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp(), validateForm()" ></p>
</form>
</body>
</html>
Instead of doing an onClick with newWindow(), askForHelp(), validateForm()
Why not just do one of them (which you want to check first) and then have the function call the others when ready?
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
} else {
newWindow(); //Validation was successful so lets open the new window
}
}
This way you can have only validateForm() trigger on click, and the rest will trigger when they need to. You'll need to add askForHelp() inside of the newWindow function to have that trigger when necessary as well.
This is sort of a shameless plug, but I just wrote an open source JS library that attempts to solve problems like this. I call it "Is".
http://jumpkick-studios.github.io/Is/
It uses the Maybe Monad concept:
http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe
So it would let you solve this problem with more of a Single Responsibility Principle.
var validateState=function(obj){
return (obj.state!=null) //error check here
}
var validateZip=function(obj){
return (obj.zip!=null) //error check here
}
var openWindow=function(){
//do open window stuff
}
var handleError(){
//handle errors here
}
var onClick=function(e){
var form={state:document.getElementById("state").value, zip:document.getElementById("zip").value})
new jumpkick.Is(form)
.is(validateState)
.is(validateZip)
.then(openWindow)
.catch(handleError)
.finally(function(){
//anything else can go here
});
}
ETA: Perhaps an even better way to approach this is to not have a single handle error function, since you may want to display messaging for each wrong field.
So maybe even something like this would work (a little more code though).
var onClick=function(e){
var validInput=true;
var state=document.getElementById("state").value, zip=document.getElementById("zip").value
new jumpkick.Is(state)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for state
});
new jumpkick.Is(zip)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for zip
});
if(validInput) // openWindow
}

Categories