javascript for loop dosn't loop through users created - javascript

OK so I am making a register and login for a forum using javascript and localstorage. "School assignment" My problem is that when i created multiple user and store them in the localstorage, my for loop does not loop through them all, only the first one. So i can only access the forum with the first user i create.
function login () {
if (checklogin()) {
boxAlert.style.display = "block";
boxAlert.innerHTML = "Welcome" + "";
wallPanel.style.display = "block";
} else {
boxAlertfail.style.display = "block";
boxAlertfail.innerHTML = "Go away, fail";
}
}
function checklogin (){
for (var i = 0; i < aUsers.length; i++){
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value){
return true;
}else{
return false;
}
}
}

how about:
function checklogin() {
var validLogin = false;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value
&& aUsers[i].password == inputLoginPassword.value) {
validLogin = true;
break;
}
}
return validLogin;
}

Ouch! You are returning false on very first attempt. The best way is to set a variable and then check for it.
function checklogin() {
var z = 0;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value) {
z = 1;
break;
} else {
z = 0;
}
if (z == 1) {
// User logged in
} else {
// Fake user
}
}

Related

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

why two $scopes updates at the same time, duplicate data

I have this piece of code
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(tempItem[index]);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(tempItem[index]);
}
}
}
}
}
I want to push data from one object to other (item to item2), it works well, but when i change data from item also item2 updates i dont want this.
What i missing?
As is, you are using an object reference. Then if modify one, the othes one is modified too.
You could use angular.copy
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
var itemCopy = angular.copy(tempItem[index]);
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(itemCopy);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(itemCopy);
}
}
}
}
}
use angular.copy to cope by value
angular.copy($scope.item1, $scope.item2);
or
$scope.item1 = angular.copy($scope.item2);

Checkboxes and trying to save the state of all checkboxes for the user when they return

function getFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
}
function fillFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
getStatus = localStorage.getItem('name'); {
if (getStatus === "true") {
console.log("its checked");
document.getElementByTagName("name").setAttribute('checked', 'checked');
} else {
console.log("its not checked");
}
}
}
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// get the form state
getFormState();
// save the state of the form each X seconds (customizable)
setInterval('fillFormState()', 1 * 1000);
}
};
But it doesn't seem to work. And Im trying to figure out why. Im not very experienced with javascript so it might be quite obvious. Sorry for that. Im trying.
I'm guessing your localStorage is never being set because of this loop:
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
There is no document.getElementByTagName, and you are also searching for "name" instead of your variable name.
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (fields[i].checked === true) { //Check the current field
localStorage.setItem(name, "true"); //Set the actual name, not "name"
} else {
localStorage.setItem(name, "false");
}
}

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

"Unable to get value of the property 'style'" when trying to change style in IE

Have written a function for cycling through the questions in a online quiz. I works fine in every browser but IE (god I wish IE would just curl up and die). Function is below.
function cycleQs() {
var qs = document.getElementsByName("quizQ");
var nextQBtn = document.getElementById("btnNextQ");
var i = 0;
var curQ = -1;
for (i = 0; i < qs.length; i++) {
if (qs[i].style.display == "block") {
curQ = i;
}
//qs[i].style.display = "none";
}
var valid = false;
if (curQ > -1) {
var qId = qs[curQ].id.replace("dv", "");
var inps = document.getElementsByName(qId);
if (inps.length > 0) {
if (inps[0].type == "radio") {
for (i = 0; i < inps.length; i++) {
if (inps[i].checked) {
valid = true;
}
}
} else if (inps[0].type == "hidden") {
valid = true;
for (i = 0; i < inps.length; i++) {
if (inps[i].value <= 0) {
valid = false;
}
}
}
} else {
valid = true;
}
} else {
valid = true;
}
if (valid == true) {
for (i = 0; i < qs.length; i++) {
qs[i].style.display = "none";
}
if (curQ < (qs.length - 1)) {
qs[curQ + 1].style.display = "block";
if (curQ == (qs.length - 2)) {
var scoreDv = document.getElementById("dvScore");
nextQBtn.style.display = "none";
var answers = getAnswers();
//alert(answers)
scoreDv.innerHTML = "Processing";
processResults(answers);
}
} else {
qs[0].style.display = "block"; // Problem occurs here when function first loads
}
} else {
alert("You must select an answer before you can proceed");
}
}
Any ideas of a work around for this?
document.getElementsByName is likely not returning anything, because of IEs implementation: see here
so qs[0] probably doesn't exist

Categories

Resources