localStorage Overwritten/ and innerHTML fail - javascript

On the 14th and 28th line, it's not changing the text of the label tag and on the recorForm or loginSetup, data is overwritten. I tried loop with .key, but it outputed the wrong stored results and I'm not sure what I did wrong. so I'm leaving it at this. What I want to know is why the innHTML of the label won't change.(I assume it's due to loading)
window.onload = alert('Window Loaded');
function recordForm() {
var userMail = document.getElementById('email').value;
var userPass = document.getElementById('password').value;
var confirm = document.getElementById('confirmation').value;
var text = document.getElemetsByClassName('errorText');
//Check that the email is not taken and confirm validation
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail.value);
localStorage.setItem('passwordz', userPass.value);
} else {
text.innerHTML = 'Password does not match!'; //line 14
}
}
function loginSetup() {
var mail = localStorage.getItem('emailz');
var pass = localStorage.getItem('passwordz');
var mailInput = document.getElementById('logEmail').value;
var passInput = document.getElementById('logPassword').value;
if ((mailInput === mail) && (passInput === pass)) {
alert(mail);
alert(pass);
} else {
text.innerHTML = 'Invalid login'; //line 28
alert('no dice');
alert(mail);
alert(pass);
}
}

You should try to store userMail.value and userPass.value. Both yet are already the values:
var userMail = document.getElementById('email').value; //Those are values already
var userPass = document.getElementById('password').value; //Those are values already
if ((userPass === confirm)) {
localStorage.setItem('emailz', userMail); //Remove the .value
localStorage.setItem('passwordz', userPass); //Remove the .value
}
Also getElementsByClassName returns a collection, thus you want to select the first item of it (assumably):
var text = document.getElemetsByClassName('errorText'); //Misstyped and no index.. wont work
var text = document.getElementsByClassName('errorText')[0]; //Should work
var text = document.querySelector('.errorText'); //Would prefer that one
At last in the function loginSetup() you have to redefine text:
var text = document.querySelector('.errorText');

Related

Calling a function by addEventListener, but the function only work one time, can not call it again

I'm trying to make a function that making the password to be text if I click the eye, if you click again, the eye will close. I may use this function for other input, so I separate the function, so I do not use the way that eye.onclick=function(){...}; Below is my code, but my code only work one time, first time I click it, the eye open, but click again, the eye can not close, is that I need to remove the EventLister?
var password = document.getElementById('passWord');
var eye = document.querySelector('#eye');
var flag = 0;
var eyeOpen = function(obj,eyes,flag){
if (flag===0){
eyes.className="eye_open";
obj.type = 'text';
flag=1;
}else{
eyes.className = "eye_close";
obj.type = 'password';
flag = 0;
}
}
eye.addEventListener('click', function () {
eyeOpen(password,eye,flag);
});
Please see the discussion here: Pass variables by reference in JavaScript. The problem is that you're passing 0 around, when what you want to be doing is changing flag directly.
var password = document.getElementById('passWord')
var eye = document.getElementById('eye')
var flag = 0
var eyeOpen = function(obj, eyes) {
if (flag === 0) {
eyes.className= 'eye_open'
obj.type = 'text'
flag = 1
} else {
eyes.className = 'eye_close'
obj.type = 'password'
flag = 0
}
}
eye.addEventListener('click', function () {
eyeOpen(password, eye)
})
The downside of this is that if you're reusing this code in several places, you could have several flags to keep track of. Rather than doing that, you could check the classList (or the input type), which would mean one less variable to keep track of:
var password = document.getElementById('passWord')
var eye = document.getElementById('eye')
var eyeOpen = function (obj, eyes) {
var isOpen = eyes.classList.contains('eye_open')
// This would also work:
// var isOpen = obj.type === 'text'
if (isOpen) {
eyes.className = 'eye_close'
obj.type = 'password'
} else {
eyes.className= 'eye_open'
obj.type = 'text'
}
}
eye.addEventListener('click', function () {
eyeOpen(password, eye)
})
var password = document.getElementById('passWord');
var eye = document.querySelector('#eye');
var flags=[0] //index based stuff
//if you have another eye..
//flags.push(0)
function openEye(index,password){
flags[index]++
if(flags[index]%2){password.type="text"}
else{password.type="password"}
}
eye.addEventListener('click',function(){
openEye(0,password) //for each eye the values can change :|
})
<input id="passWord" type="password"/>
<button id="eye">THE EYE</button>

jQuery check multiple CSV lists

To simplify my problem i rewrote the code without the parsing of CSV, but instead with a variable that holds the data.
--CODE EDIT---
$(document).ready(function() {
var qID = 'xxx';
var source = ['text1', 'text2', 'etc3'];
var source2 = ['text4', 'text5', 'etc6'];
$('#question' + qID + ' input[type="text"]').change(function() {
var validVal = 0;
var inputVal = $(this).val();
// Loop through the text and test the input value
$(source).each(function(i) {
if (inputVal == this) { // If a match is found...
validVal = 1;
}
});
// If a valid text was entered
if (validVal == 1) { // A valid input
alert("GOOD");
} else { // An invalid input
alert("NOT GOOD");
}
var validVal2 = 0;
var inputVal2 = $(this).val();
$(source2).each(function(j) {
if (inputVal2 == this) { // If a match is found...
validVal2 = 1;
}
});
// If a valid text was entered
if (validVal2 == 1) { // A valid input
alert("GOOD2");
} else { // An invalid input
alert("NOT GOOD2");
}
});
});
The script works fine for one source (var source) but i want to check in the same text field 2 variables (source, source2) that will produce different alerts.
The script is run through a limesurvey form and the input is a simple [type="text"] field.
How do I check for 2 different arrays of text in the same text field?
Whenever you find yourself putting counters on variable names to create a series, you need to stop and think about what you are actually doing there. Making counted variable names is always wrong.
Use arrays.
var qID = 'xxx';
var source = [];
source.push(['text1', 'text2', 'etc']);
source.push(['text1', 'text2', 'etc44']);
source.push(['text15', 'text25', 'etc454']);
$('#question' + qID + ' input[type="text"]').change(function() {
var valid = false;
var inputVal = $(this).val();
$.each(source, function(i, terms) {
$.each(terms, function(i, term) {
valid = inputVal === term;
return !valid; // returning false stops the .each() loop
});
return !valid;
});
if (valid) {
alert("GOOD");
} else {
alert("NOT GOOD");
}
});
A more appealing way to express the nested loop above uses built-in methods of Array.
var valid = source.some(function (terms) {
return terms.includes(inputVal);
});
in ES6 syntax this can be made a one-liner:
var valid = source.some(terms => terms.includes(inputVal));

why my alert shows undefined in javascript

var database = require('../../db');
var rightponame = '1';
var rightdevname = '';
var rightpopassword = '';
var rightdevpassword = '';
database.db.once('open', function() {
console.log('success');
var cursor = database.db.collection('user').find({}, {
_id: 0
});
cursor.each(function(err, doc) {
if (doc != null) {
rightponame = doc.productOwner;
rightdevname = doc.developer;
rightpopassword = doc.popassword;
rightdevpassword = doc.devpassword;
console.log(rightponame);
console.log(rightdevname);
console.log(rightpopassword);
console.log(rightdevpassword);
} else {
console.log('o');
}
});
});
function login() {
var getusername = document.getElementById("username").value;
var getpassword = document.getElementById("password").value;
alert(rightponame);
}
Finally, I get rightponame, rightdevname, rightpopassword and rightdevpassword value. But in the login function, I get undefined in the alert.
Why?
In JavaScript, alert is only available in the browser. It appears you're using node.js or the like. Try console.log instead, as you're doing on db open.
Then when you check the terminal window where the process is running, you should see the value of console.log.
Since console.log takes multiple values, it's helpful to prefix with something distinguishable like:
console.log('<<<<<<<', rightponame)

How to write loops for field validation

I'm trying to figure out why validation is always fails? Regular expressions should be fine, I guess the problem should be somewhere in if(loginreg.test(login) && passwordreg.test(password) && repassword==password). Could someone please help me with it?
function CheckAuthData() {
var loginreg = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{4,}\d$/g;
var login = document.getElementById("login").value;
var passwordreg =
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{1,}$/g;
var password = document.getElementById("password").value;
var repassword = document.getElementById("repassword").value;
if(loginreg.test(login) && passwordreg.test(password) && repassword==password){
document.getElementById("labellogin").innerHTML = "";
document.getElementById("labelpassword").innerHTML = "";
document.getElementById("labelrepassword").innerHTML = "";
document.getElementById("pers_data").style.display = "block";
}
if(!loginreg.test(login)){
var label = document.getElementById("labellogin").innerHTML = "Login error!";
document.getElementById("labellogin").style.color = "red";
}
if(!passwordreg.test(password)){
document.getElementById("labelpassword").innerHTML = "Password error!";
document.getElementById("labelpassword").style.color = "red";
}
if(repassword!=password){
document.getElementById("labelrepassword").innerHTML =
"Should be the same password!";
document.getElementById("labelrepassword").style.color = "red";
}
}
The only actual error I can see there is that if any of those conditions fails once, you never clear the red off the element where it happened. But since you clear the text out of the element, it probably doesn't matter.
That said, testing the same conditions twice (in your first if and then again in subsequent ones, inverted) is a maintenance problem waiting to happen, as is all of the repeated code in the function.
You also don't need to recreate the regular expressions every time the function is called, and you don't need the g flag on them.
This addresses the various issues above (note: I'm assuming this is contained in some kind of scoping function, so we're not creating new globals by moving those regexes out):
var loginreg = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{4,}\d$/;
var passwordreg =
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{1,}$/;
function CheckAuthData() {
var login = document.getElementById("login").value;
var password = document.getElementById("password").value;
var repassword = document.getElementById("repassword").value;
var failed = false;
updateField("labellogin", loginreg.test(login), "Login error!");
updateField("labelpassword", passwordreg.test(password), "Password error!");
updateField("labelrepassword", repassword == password, "Should be the same password!");
if(!failed) {
document.getElementById("pers_data").style.display = "block";
}
function updateField(id, valid, message) {
var element = document.getElementById(id);
element.innerHTML = valid ? "" : message;
element.style.color = valid ? "" : "red";
failed = failed || !valid;
}
}
Made this a CW because...well...it probably doesn't actually answer the question, because there isn't enough info in the question. But hopefully it's helpful.

Loading form input fields into a javascript array and then validating

I seem to be really stuck on something. I have a function to check if all the form input fields are equal to null or "" which is all fine but wanted to see if there is another way of doing it by loading all the fields into a javascript array and then doing a for loop along with an if statement to check if any of the fields are empty, unfortunately I can't seem to get this to work and wondering if I've simply just missed something some where. Here is my code:
function checkempty()
{
fname = document.getElementById("firstname").value;
lname = document.getElementById("lastname").value;
fage = document.getElementById("age").value;
addressl1 = document.getElementById("addressline1").value;
addressl2 = document.getElementById("addressline2").value;
ftown = document.getElementById("town").value;
fcounty = document.getElementById("county").value;
fpcode1 = document.getElementById("pcode1").value;
fpcode2 = document.getElementById("pcode2").value;
ftelephone = document.getElementById("telephone").value;
fcomment = document.getElementById("comment").value;
var myArray = [];
myArray[0] = fname;
myArray[1] = lname;
myArray[2] = fage;
myArray[3] = addressl1;
myArray[4] = addressl2;
myArray[5] = ftown;
myArray[6] = fcounty;
myArray[7] = fpcode1;
myArray[8] = fpcode2;
myArray[9] = ftelephone;
myArray[10] = fcomment;
for(i=0;i<myArray.length;i++)
{
if(!myArray[0])
{
return true;
}
}
return false;
}
I then use another function:
function checkform()
{
if(checkempty)
{
display_errormessage("One or more fields empty!");
}
else
{
alert("Thanks for you input!");
}
}
The display_errormessage() function is just one that puts an error message into a div at the top of the form to display an error message if the form is incomplete.
Can anyone see where i've gone wrong?
Thanks in advance for any help!
Dave.
First, function checkform is not called. The if (checkform) should be if (checkform()) or you will test only test the availability of the function, not the result.
Then the if (!myArray[0]) should be if (!myArray[i]) to not only test the firstname
Or better, if (myArray[i].length==0) to be sure to explicitly test for empty string and not just doing an implicit boolean conversion (javascript evaluate 0=="" as true)
if(!myArray[0]) should be if(!myArray[i]), but a larger point is you're only validating that the value isn't falsey (null, '', 0, false, etc.), not that it's appropriate for the task.
Guess you won't need this function as you've already fixed yours, but I'll leave it here as it may be helpful in the future. JSFiddle
function checkform()
{
arr1 = document.getElementsByTagName('input');
arr1 = Array.prototype.slice.call(arr1);
arr2 = document.getElementsByTagName('textarea');
arr2 = Array.prototype.slice.call(arr2);
arrs = arr1.concat(arr2);
for(i=0;i<arrs.length;i++)
{
if (arrs[i].type == "text" || arrs[i].type == "textarea")
{
if (arrs[i].value == '')
{
alert("Fill all fields before submitting!");
return false;
}
}
}
alert("Thanks for your input!");
return true;
}
According that your input fields are in the form named form:
var allTrue = [].every.call( document.forms.form.elements, function( el ) {
return !!el.value;
} );
if ( allTrue ) {
alert( "Thanks for your input!" );
}
else {
alert( "Some fields are missing!" );
}

Categories

Resources