Form validation !='' in if statement? - javascript

Can anyone tell me whats wrong with this code, im validating a form making sure all the fields have text in them before anyone can submit. everything works until i put in the !='' var. I am sure the id's are correct
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script language="javascript">
$(document).ready(function() {
// declare the flags outside the other functions
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready && emailvalue!='' && usernamevalue!='' && firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
}
else {$("#register").prop('disabled',true);}
}
and here is my form code so you can see if thats the issue...
<p>First Name: <input id="first" type="text" name="name" maxlength="100"> </p>
<p>Last Name: <input id="last" type="text" name="name" maxlength="100"> </p>
<p> Email: <input type="text" name="email" id="email" maxlength="100" />
<span id="box" style="display:none"></span></p>
User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
<span id="msgbox" style="display:none"></span>
<p> Password: <input id="password" type="password" name="password"> </p>

You spelt your variable name firstvalue incorrectly:
firstvale!=''
Edit
Move these 5 lines:
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
From where they are to right under function checkSubmitStatus(){ and above your big if statement.
Where they are now, they are only assigned once, to the value of the form when the page first loads which I'm assuming at least one of them is empty.
You need to move those lines into your checkSubmitStatus() function so that they get updated whenever the function is called. The final result should look like:
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready &&
emailvalue!='' && usernamevalue!='' &&
firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
} else {
$("#register").prop('disabled',true);
}
}

Judging from your code, I get the feeling that it's copy-pasted together from different parts of your code. What might be happening is that emailvalue, usernamevalue etc are really out of scope at the time the checkSubmitStatus is called. I might also be wrong, but it's hard to tell more based on the provided code, since it seems to be alright.
You could do alert(emailvalue); before the if statement to see if you get undefined or some value. If it's undefined, you probably have a scope issue.
From the above code it also seems that you assign those variables values, before anything is really entered or the form is submitted.

Related

JavaScript Alert message not working

Below is the code that I have put together to validate 5 fields, of a form that has like 9 fields, that are to be required. I created the variables and placed them into an array. From there I have a function that loops through this array to see pop up an alert if that field is left blank.
The problem that I am coming across is that the alerts are not popping up when the button is clicked.
var uName=document.getElementByName('userName');
var pword=document.gelElementByName('password');
var verify=document.getElementByName('passwordVerify');
var fName=document.getElementByName('firstName');
var lName=document.getElementByName('lastName');
var field=[uName,pword,verify,fName,lName];
function validateForm(form) {
for(var i = 0; i < form.field.length; i++){
if(form.field[i].value.length == 0){
alert(form.field[i].name+' is required. Please populate');
form.field[i].focus();
return false;
}
} return true;
}
Not sure what I did wrong or what is causing the error. Any assistance is greatly appreciated.
function validateForm() {
var uName = document.getElementById('userName');
var pword = document.getElementById('password');
var verify = document.getElementById('passwordVerify');
var fName = document.getElementById('firstName');
var lName = document.getElementById('lastName');
var field = [uName, pword, verify, fName, lName];
for (var i = 0; i < field.length; i++) {
if (!field[i].value) {
alert(field[i].name + ' is required. Please populate');
field[i].focus();
return false;
}
}
return true;
}
<form>
<input type="text" id="userName" name="userName" /><br/>
<input type="text" id="password" name="password" /><br/>
<input type="text" id="passwordVerify" name="passwordVerify" /><br/>
<input type="text" id="firstName" name="firstName" /><br/>
<input type="text" id="lastName" name="lastName" /><br/>
<button onclick="validateForm();">Submit</button>
</form>
Now, here are the changes I made:
I changed getElementByName to getElementById throughout your code, for simplicity;
I removed the function's parameter, and changed form.field to field because... Well, the first one was just wrong.
I also changed the iterating test to !field[i].value, which is equivalent to testing if the value has a length, but seemed more appropriate to me.
That's about all I did, along with adding ID's to the form's elements.
P.S: That is my first detailed answer here, feedback would be greatly appreciated! :)

Why am i getting " Uncaught TypeError: Cannot read property 'addEventListener' of undefined"

I can't figure out why i am getting this error: "Uncaught TypeError: Cannot read property 'addEventListener' of undefined "
Here is the code:
HTMl
<form method="post" action="" id="security-check">
<input type="text" name ="first" placeholder="First Name">
<input type="text" name ="last" placeholder="Last Name">
<input type="number" name ="dob" placeholder="DOB">
<input type="text" name ="state" placeholder="State">
<input type="submit" value="submit">
</form>
JavaScript
var input = document.getElementsByTagName('input');
var fname = input[0];
var lname = input[1];
var dob = input[2];
var rez = input[3];
function idCheck(first, last, date, state){
this.first = "Teddy";
this.last = "Broosevelt";
this.date = 03041894;
this.state = "NY";
if(firstName != this.first){return false;};
if(lastName != this.last ){return false;};
if(birthDate != this.date){return false;};
if(rez != this.state){return false;};
}
input[4].addEventListener('submit', function(e){
idCheck(fname, lname, dob, rez);
e.preventDefault();
}, false);
Cannot read property addEventListener of undefined simply means that your attempt to use the addEventListener method of some object can't work because the object that you are trying it on isn't really an object it's "undefined".
So, input[4] is the object qualifier you have before addEventListener, so input[4] is what is undefined. You must examine your code to determine why that is. As others have said, you most likely don't have a 5th element being returned to your input nodelist varaible.
EDIT:
Now that you've posted more of your code, there are many problems. The biggest of which is that you are wiring up your event handler incorrectly so it will never get called. See my updates to your code and comments below:
<html>
<head>
</head>
<body>
<!-- Don't use hypens in element ids -->
<form method="post" action="#" id="securityCheck">
<input type="text" name="first" placeholder="First Name">
<input type="text" name="last" placeholder="Last Name">
<input type="number" name="dob" placeholder="DOB">
<input type="text" name="state" placeholder="State">
<input type="submit" value="submit">
</form>
<script>
// If you wish to work with form events, you need a reference to your form:
var form = document.getElementById("securityCheck");
var input = document.getElementsByTagName('input');
var fname = input[0];
var lname = input[1];
var dob = input[2];
var rez = input[3];
function idCheck(first, last, date, state) {
this.first = "Teddy";
this.last = "Broosevelt";
// This should be a date. You had it as a number and that
// number could be interpreted as an octal because it starts with 0
this.date = new Date(1894, 2, 4); // Month is zero-based
this.state = "NY";
// Where are firstName, lastName and birthDate being declared?
if (fName != this.first) { return false; };
if (lName != this.last) { return false; };
if (dob != this.date) { return false; };
if (rez != this.state) { return false; };
}
// You are attempting to wire up a submit button to the submit
// event, but a submit button does not have this event, the form does
form.addEventListener('submit', function (e) {
// Calling idCheck may result in a return value of false
// or it may result in nothing of consequence happening
// Either way, you are not doing anything with what may
// or may not come back from idCheck. All this function really
// does is ensure that the form never submits
idCheck(fname, lname, dob, rez);
e.preventDefault();
}, false);
</script>
</body>
</html>

TypeError: document.getElementById(...); is null in Javascript

All of my var statements uses identifiers:
var identifier = document.getElementById("somename");
So why am I getting a null error?
I ran this code in the Javascript runner and got the null error message. And in my browsers Firefox and Chrome I don't get any errors or warnings. When I run the code in the browser and click the button to activate the event handler, the form clears. It's not going to a server anyway. It's just practice. I'm taking a course in javascript and Dynamic HTML. If anybody care to look at my code and tell me what I'm doing wrong I'd appreciate it.
There's got to be something that I'm not getting right. Here is the script:
window.onload = function(){
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
if(document.getElementById("uname").value == ""){
return false;
alert("Your user name can't be blank.");
};
if(pass1.value !== pass2.value){
get.documentElementById("signin").value.disabled = true;
return false;
alert("Please retype your password.");
}else if(pass1.value === pass2.value){
alert("Welcome!");
};
};
HTML
<body>
<form action = "" name = "form" method = "Post">
<label for="fname">First Name:</label><input type = "text" id = "fname"required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type = "text" id = "uname" required></input><br/>
<label for="password1">Password:</label><input type = "password" id = "password1"required ></input><br/>
<label for="password2">Verify Password:</label><input type = "password" id = "password2"required ></input><br/>
<label for="email">Email Address:</label><input type = "email" id = "email" required></input><br/>
<button type = "submit"id = "signin" onclick = "function()">Submit</button>
</form>
<script src="signUp.js"></script>
</body>
I cleaned up your code for you. There were several spots where you had errors (e.g., typing pass1.value instead of just pass1. This should work, but of course take time to study it to see what I changed and understand why. Here's a fiddle showing it working. Note that you should never expect this type of code to run in the "runners" that you've made reference to; the code here makes explicit reference to particular elements in the DOM, which the runners won't have. (Using a site like JSFiddle is better for this sort of thing, since you can put HTML into it as well).
var submitForm = function () {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
console.log(pass1, pass2);
if (document.getElementById("uname").value == "") {
alert("Your user name can't be blank.");
return false;
}
if (pass1 !== pass2) {
document.getElementById("signin").value.disabled = true;
alert("Please retype your password.");
return false;
} else if (pass1 === pass2) {
alert("Welcome!");
}
};
<body>
<form action="" name="form" method="POST">
<label for="fname">First Name:</label><input type ="text" id = "fname" required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type ="text" id ="uname" required></input><br/>
<label for="password1">Password:</label><input type="password" id="password1" required></input><br/>
<label for="password2">Verify Password:</label><input type="password" id="password2" required ></input><br/>
<label for="email">Email Address:</label><input type="email" id="email" required></input><br/>
<button type="submit" id="signin" onclick="submitForm()">Submit</button>
</form>
</body>

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Javascript text field validation

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;
You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>
Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.

Categories

Resources