Why is my div not updating properly? - javascript

So my code basically is to tell users what's wrong in their registration, everything works but one thing. The Div should update the text field to say what's wrong with their registration, but it is not, here is my JavaScript
window.onload = initPage;
submitBtn = document.getElementById("submit");
errorText = document.getElementById("errortext");
function initPage() {
document.getElementById("password2").onkeyup = checkPassword;
document.getElementById("password2").onblur = checkPassword;
document.getElementById("email2").onkeyup = checkEmail;
document.getElementById("email2").onblur = checkEmail;
submitBtn.disabled = false;
}
function checkPassword() {
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
if (password1 != password2) {
document.getElementById("password1").className = "denied";
document.getElementById("password2").className = "denied";
submitBtn.disabled = true;
document.getElementById("submit").className = "denied";
errorText.innerHTML = "Passwords do not match.";
} else {
document.getElementById("password1").className = "password2";
document.getElementById("password2").className = "password2";
document.getElementById("submit").className = "button1";
submitBtn.disabled = false;
errorText.innerHTML = "";
}
}
function checkEmail() {
var email1 = document.getElementById("email1").value;
var email2 = document.getElementById("email2").value;
if (email1 != email2) {
document.getElementById("email1").className = "denied";
document.getElementById("email2").className = "denied";
submitBtn.disabled = true;
document.getElementById("submit").className = "denied";
errorText.innerHTML = "Emails Do Not Match.";
} else {
document.getElementById("email1").className = "regtext";
document.getElementById("email2").className = "regtext";
submitBtn.getElementById("submit").disabled = true;
document.getElementById("submit").className = "button1";
errorText.innerHTML = "";
}
}
here is my div
<tr><td colspan="2"><div id="errortext"></div></td></tr>

You're probably trying to access that div before the DOM is fully constructed. Put that code in with the initPage function. You'll need a variable outside of the scope of that function so your other functions can access them. You should put all of this in a closure to avoid creating global variables.
Ex:
(function(){
var submitBtn;
var errorText;
function initPage() {
submitBtn = document.getElementById("submit");
errorText = document.getElementById("errortext");
document.getElementById("password2").onkeyup = checkPassword;
document.getElementById("password2").onblur = checkPassword;
document.getElementById("email2").onkeyup = checkEmail;
document.getElementById("email2").onblur = checkEmail;
submitBtn.disabled = false;
}
// This next line should be under the declaration above
window.onload = initPage;
// ...
})();

You have to fetch the element by id and then sets its inner html.
document.getElementById("errorText").innerHTML = "Emails Do Not Match.";
and do the same where ever you are using errorText.innerHTML directly.

Related

How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. Where I am storing the user data in an array and then in local storage. For this I have initially declared an empty array called var users=[];
Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. Please help, on how to avoid the array become empty after reloading the page.
Following is my controller.js-
//Declaring an empty array
var users = [];
//Setting id for each users
var idInput = makeCounter();
//Fetching data from textboxes in register.html
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var dobInput = document.getElementById("dob");
var messageBox = document.getElementById("editeddata");
//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.dob = dob;
this.username = username;
this.password = password;
this.FullName = this.firstname +' ' + this.lastname;
}
//counter funtion, to fetch user id
function makeCounter() {
var arraylength=users.length;
return function(){
return arraylength+1;
}
}
//insert data while registration
function registerUser()
{
//Email validation
var emailinput = document.forms["myform"]["email"].value;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!(emailinput).match(emailReg) || emailinput=="")
{
alert("Not a valid e-mail address");
return false;
}
//check, if fields are empty
if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
{
alert("Fields cannot be empty");
return false;
}
//check, if a user already exist
var usernameinput = document.forms["myform"]["username"].value;
var passwordinput = document.forms["myform"]["password"].value;
var ulen= users.length;
for(i=0; i < ulen; i++)
{
if ( usernameinput == users[i].username && passwordinput == users[i].password)
{
alert("User already exists");
return false;
}
}
var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
users.push(user);
alert("Registered successfully");
localStorage.setItem("key_users", JSON.stringify(users));
}
You can use local storage value at the time of initialisation.
if (typeof(Storage) !== "undefined") {
if (localStorage.key_users) {
users = localStorage.key_users;
} else {
users = [];
}
}
you can use something like this to check if the key is already in localStorage or not.
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body onload="test()">
<script>
function test(){
var value = (localStorage.getItem("key1"))
console.log(value)
if(value == null){
localStorage.setItem("key1","value1")
alert("Hellow")
}else{
var value=localStorage.getItem("key1");
alert(value)
}
}
</script>
</body>
</html>

Why is my Javascript form validation not working properly?

Why is my validation failing on second attempt here? On first attempt the validation works fine, but on the second run, it will accept inappropriate values in the email field. The first two fields work fine, but the third field will accept any text after the first run. However it only validates if I change the value in the email field, otherwise it will keep displaying the error and failing to validate like it should.
function validate(){
clearErrors();
var errorFlag = true;
var name = document.getElementById("name");
nameVal = name.value;
if(nameVal.length === 0){
var nameError = document.getElementById("nameError");
nameError.style.display = "block";
errorFlag = false;
}
var phone = document.getElementById("phone")
var phoneVal = phone.value;
if(isNaN(phoneVal) || (phoneVal < 1000000000 || phoneVal >10000000000)){
errorFlag = false;
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "block";
}
var email = document.getElementById("email");
var emailVal = email.value;
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
errorFlag = false;
var emailError = document.getElementById("emailError");
emailError.style.display = "block";
}
return errorFlag;
}
function clearErrors(){
var nameError = document.getElementById("nameError");
nameError.style.display = "none";
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "none";
var emailError = document.getElementById("emailError");
emailError.style.display = "none";
}
Your validator will fail on the email, because you are feeding a string to .match, when it needs a regex.
You also have to call .match on the email itself, with the regex as the argument.
You also need to negate the return value to check if it does not match, or use .test.
This bit:
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
Should be replaced with:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!emailVal.match(re)){
Of if you can't use a regex literal for some reason:
var re = new RegExp("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
if(!emailVal.match(re)){
Or using .test instead of .match:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!re.test(emailVal)){
Note the i for case-insensitive matching, so emails don't have to be entered in all-caps.

JavaScript error with splitting string into array

I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Creating a login in javascript - array comparison

I have a login box using a simple javascript login comparing usernames and passwords, before you all start I know about the security issues in using javascript for authentication. Here is the code
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters", "Jonathan Goss", "Lisa Cain", "Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
document.getElementById("mandatory1").value = un;
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
At the moment if the login is successful I'm posting the username to a hidden field which is then being used by a piece of a software. How do I associate the names in fnArray with the other correct username & password so that I can then grab associated full name and post that to the hidden field "mandator1" instead?
You can get the index of the correct user
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters, Jonathan Goss, Lisa Cain, Jenny Dempsey"];
var index = 0;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
index = i;
break;
}
}
now you can access the correct data using
unArray[index];
// and so on for other arrays
Define a variable for full name, and set it if you have the valid user:
var fn = "";
/* ... */
valid = true;
fn = fnArray[i];
/* ... */
document.getElementById("mandatory1").value = fn;
Note: Actually you can check validity later on using fn. If it is empty string, then no user was logged in. This makes it have same purpose as valid, and more.
Try this.
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = -1;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters","Jonathan Goss","Lisa Cain","Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = i;
break;
}
}
if (valid != -1) {
alert ("Login was successful");
document.getElementById("mandatory1").value = fnArray[valid];
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
set mandatory1 when the login is successful based on i (in the for loop)

Categories

Resources