Function never triggered by getElementById().addEventListener() - javascript

I'm attempting to move JavaScript event triggers on the two password fields (to alert the user if they're not equal) from within the form elements to
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
But the function is never triggered (if I change checkPass to checkPass() the function is called on page-load only, but I don't think this means it's being triggered by the listener). There are no errors in the JavaScript console. If I change the ids to something bogus, it gives this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
(I'm not familiar enough with the Chrome JavaScript inspector, to know if it can help me further.)
It all works properly if the event triggers are directly in the form elements.
Here are the form elements:
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
What am I missing?
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/">
<p>Username: <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
<span id="confirmMessage" class="confirmMessage"></span>
<input type="submit" name="submit" value="Register" />
</form>
<script language="JavaScript">
function checkPass() {
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
alert("pass1=" + pass1.value + ", pass2=" + pass2.value);
//Check passwords here. Set confirmMessage if bad.
}
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
</script>
</BODY></HTML>

The event is case sensitive. Try "keyup" (all lowercase) instead. See this fiddle:
http://jsfiddle.net/LfamexLw/
function checkPass(){
alert("keyup");
}
function checkPass2(){
alert("keyUp");
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password1').addEventListener('keyUp', checkPass2);
You'll notice checkPass2 never fires.

Here's the working code, based on #aquinas' answer, including the full check-the-password function:
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/"
enctype="multipart/form-data">
<p><label for="id_username">Username:</label> <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p><label for="id_password1">Password:</label> <input id="id_password1" name="password1" type="password" /></p>
<p><label for="id_password2">Password confirmation:</label> <input id="id_password2" name="password2" type="password" /></p>
<!-- Where checkPass() writes its message -->
<span id="confirmMessage" class="confirmMessage"></span>
<P><input type="submit" name="submit" value="Register" /></P>
</form>
<script language="JavaScript">
/*
From (8/27/2014)
http://keithscode.com/tutorials/javascript/3-a-simple-javascript-password-validator.html
Added the "don't print anything if one or both fields are empty" block
*/
function checkPass() {
//Store the password field objects into variables ...
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value.length === 0 || pass2.value.length === 0) {
pass2.style.backgroundColor = null;
message.style.color = null;
message.innerHTML = "";
return;
}
if(pass1.value === pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password2').addEventListener('keyup', checkPass);
document.getElementById("id_username").focus();
</script>
</BODY></HTML>

Related

Form Validation not responding correctly

I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Using JavaScript to validate form both onblur and when pressing submit

I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Multiple Validation checks - logic error

I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>

Categories

Resources