Changing the boolean value of an object stored in array - javascript

I'm just starting my journey with JS so pleace be patient :)
I'm building a small app. The images on the left side are stored in an array. If someone clicks one of them I want to change its height but also the boolean value from false to true so that I know which one the user clicked (for further purposes). In my mind it goes like this: creating an array->add EventListener to the item->chain it witch the function choosen(change the value to true)->run setClick function that changes the height. What's wrong there?
I aprecciate any advice.
CODEPEN http://codepen.io/finewitch/pen/ZBKMKm
var storage = new Array();
storage[0] = document.getElementById("grandFatherCh");
storage[1] = document.getElementById("grandMotherCh");
storage[2] = document.getElementById("sisterCh");
storage[3] = document.getElementById("brotherCh");
storage[4] = document.getElementById("fatherCh");
storage[5] = document.getElementById("motherCh");
storage[0].clicked = false;
storage[1].clicked = false;
storage[2].clicked = false;
storage[3].clicked = false;
storage[4].clicked = false;
storage[5].clicked = false;
for (var i=0; i<storage.length; i++){
storage[i].addEventListener("click",choosen, setClick);
console.log("clicked");
};
function choosen(){
if (storage[i].clicked == false)
{
return "stillFalse"
storage[i].clicked = true;
}
};
function setClick(){
if(storage[i].clicked === true){
return "setClickWorks"
storage[i].style.height = "400px";
}else{
console.log('failed');
}
};

Maybe I'm missing something but I think you have the return statement in the wrong place no? Should be
function choosen(){
if (storage[i].clicked == false) {
return "stillFalse"
} else {
storage[i].clicked = true;
}
}
function setClick(){
if (storage[i].clicked === true){
storage[i].style.height = "400px";
return "setClickWorks"
} else {
console.log('failed');
}
}

Related

Getting True/False values from Firebase if a tree/value exists. Cannot get this to work

Been at this all day. I am building a social network.
It checks to see if two users have connected to each other, if they have a structure like this is created.
ROOT->Groups->RequestingUser->UserTheyWant
When two people have each requested each other, I want two variables to compare so if both are true I can continue. I can not get this to work.
I have tried so many iterations of this but I cannot get true/false values from this, I don't want to post all my attempts... Hopefully this gets it across.
I just need the two functions didYouRequest and didTheyRequest to return true/false OR didTheVisitorConnect / checkIfOtherProfilePersonConnected actually set outside the damn function so i can compare them.
$scope.connect = () => {
// my userid -> and set key in there for who they want to visit
console.log('added ' + $scope.profile.name + ' as friend.');
return fbGroupsDb.child(userLoggedIn).child(userUID).set(
{
connected: true
});
};
var didTheVisitorConnect = false;
$scope.didTheVisitorConnect = false;
var checkIfOtherProfilePersonConnected = false;
$scope.checkIfOtherProfileConnected = false;
var didYouRequest = fbGroupsDb.child(userLoggedIn).child(userUID).once('value').then( function (snapshot) {
if (snapshot.val() !== null) {
$scope.didTheVisitorConnect = true;
didTheVisitorConnect = true;
console.log('Did You Request? : ', didTheVisitorConnect);
return true;
} else {
$scope.didTheVisitorConnect = false;
didTheVisitorConnect = false;
console.log('Did You Request? : ', didTheVisitorConnect);
return false;
}
});
var didTheyRequest = fbGroupsDb.child(userUID).child(userLoggedIn).once('value').then( function (snapshot) {
if (snapshot.val() !== null) {
$scope.checkIfOtherProfileConnected = true;
checkIfOtherProfilePersonConnected = true;
console.log('Have they requested You? : ', checkIfOtherProfilePersonConnected);
return true;
} else {
$scope.checkIfOtherProfileConnected = false;
checkIfOtherProfilePersonConnected = false;
console.log('Have they requested You? : ', checkIfOtherProfilePersonConnected);
return false;
}
});
You seem to be looking for
Promise.all([didYouRequest, didTheyRequest]).then(function([you, they]) {
if (you && they) {
…
} else {
…
}
});

Matching text in element with Protractor

I have an element on page. And there could be different text. I am trying to do like (code is below), and it is not printed to console.
this.checkStatus = function () {
var element = $('.message')
browser.wait(EC.visibilityOf(element), 5000).then(function () {
browser.wait(EC.textToBePresentInElement(conStatus, 'TEXT1'), 500).then(function () {
console.log('TEXT1');
})
browser.wait(EC.textToBePresentInElement(element, 'TEXT2'), 500).then(function () {
console.log('TEXT2');
})
browser.wait(EC.textToBePresentInElement(element, 'TEXT3'), 500).then(function () {
console.log('TEXT3');
})
browser.wait(EC.textToBePresentInElement(element, 'TEXT4'), 500).then(function () {
console.log('TEXT4');
})
})
return this;
}
thanks
I see two problems. first, not sure what 'constatus' is? you need to correct that. second, browser.wait will be throwing error/exceptions when it is not able to find matching condition and timeout expires, So, if your first condition doesn't meet, it will throw timeout exception and will never go to second one. Instead, try something like below
var section = "";
this.checkStatus = function () {
var element = $('.message')
browser.wait(EC.visibilityOf(element), 5000).then(function () {
browser.wait(()=>{
if(EC.textToBePresentInElement(element, 'TEXT1')){
section = "Text1";
}
else if(EC.textToBePresentInElement(element, 'TEXT2')) {
section = "Text2";
}
else if(EC.textToBePresentInElement(element, 'TEXT3')) {
section = "Text3";
}
else if(EC.textToBePresentInElement(element, 'TEXT4')) {
section = "Text4";
}
if(section !== "")
return true;
}, 5000).then(()=>{
<here you can do anything based on 'section'>
}
Note - I haven't verified compilation errors.. so check for that.
Not sure what are you up to, but you can join multiple expected conditions with "or":
var conStatus = $('.message');
var containsText1 = EC.textToBePresentInElement(conStatus, 'TEXT1');
var containsText2 = EC.textToBePresentInElement(conStatus, 'TEXT2');
var containsText3 = EC.textToBePresentInElement(conStatus, 'TEXT3');
var containsText4 = EC.textToBePresentInElement(conStatus, 'TEXT4');
browser.wait(EC.or(containsText1, containsText2, containsText3, containsText4), 5000);

Backbone data logic inside view

I am not sure where to perform the action of preparing the data for the template of my view. Currently I have this piece of code.
getTemplateData: function () {
var inventoryStatus = selectedDevice.get("inventoryStatus"),
data = {},
statusName,
inventoryDate;
statusName = getConfigValue("pdp", "statusMap", inventoryStatus);
data.message = getConfigValue("pdp", "statusMessage", statusName);
data.className = "";
data.dataAttribute = null;
data.tooltipValue = null;
data.displayError = false;
var redirectCode = (allDevices.get("thirdPartyRedirectCode") !== null) ? allDevices.get("thirdPartyRedirectCode") : "";
if (redirectCode) {
if (redirectCode === 9999) {
data.buttonDisabled = false;
data.buttonText = "Design Yours";
} else if (redirectCode === 9998) {
data.buttonDisabled = true;
data.buttonText = "Design Yours";
}
return false;
}
switch(inventoryStatus) {
case 1001: //Out of Stock
data.buttonDisabled = true;
data.displayError = true;
break;
case 1002: //Pre Order
data.buttonDisabled = false;
break;
}
return data;
}
This getTemplateData() I call inside my render function of the view. This seems wrong by the looks of it and i am unsure where to place this code.
Should I create different getters in my model or should i leave them inside my main view. Please help.
From what I know the "correct" way of doing this is to put it in the model, and in the view have
getTemplateData: function () {
return this.model.getTemplateData();
}
EDIT
In case of multiple models for a view (which shouldn't happen, without getting into your decisions at the moment) you can have a getTemplateData for each, and call them with something like extend:
getTemplateData: function () {
var data = this.model1.getTemplateData();
data = $.extend(data, this.model2.getTemplateData());
return data;
}
BUT
What you really should do, IMHO, is give each it's own view, where one of them is smaller and intended to be included in the other. (i.e. bigView.$el.append(smallView.el))

How to get my loop to start from the beginning after error detected

I am trying to get my loop to restart when it comes across an user input error. I need it to restart at the very beginning and not just the last question.
So below when it says validImput = false this is where I am trying to get it to restart.
{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {
// ask first question
var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
if (isNaN(orderProductCodeArr)) {
alert("input is not a valid number");
validImput = false
} else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
alert("code does not match any item");
validInput = false;
}
// ask second question
else if(validInput == true) {
var item = PRODUCT_LIST[orderProductCodeArr];
alert("item is: " + item);
}
// get quantity input
var quanityArr = parseInt (prompt('Enter quality amount'),10);
if (isNaN(quanityArr)) {
alert("input is not a valid number");
validInput = false;
}
} else {
document.writeln('still to come')
}
}
The usual method of starting something over is some sort of loop construct, often using while like this:
while (true) {
// your loop code here
// you can use break; to break out of the while loop
// anywhere to stop repeating
// you can use continue; to jump to the next iteration immediately
}
Or, sometimes you use a loop condition like this:
var doAgain = true;
while (doAgain) {
// within the loop, you set doAgain to false when you are done
// and don't want to repeat the loop again
}
try
function test()
{
for(var s=0;s<5;s++)
{
try
{
//body of the for loop
}catch(e){s=0;}
}
}

Problem with form validation (phone numbers)

Ok, I have a validation script that checks everything on the form - but it flags the phone number fields as wrong regardless of whats in there. I've tried it a couple different ways and I cant figure out what I am doing wrong.
The part of the script that validates is...
if (testPattern(phone1, /^\d{3}$/)== false) { // checking phone length
valid = false;
}
if (testPattern(phone2, /^\d{3}$/)== false) {
valid = false;
}
if (testPattern(phone3, /^\d{4}$/)== false) {
valid = false;
}
The function code is...
function testPattern(field, reg2) {
var trueOrfalse = reg2.test(field)
if (trueOrfalse == false) {
field.style.backgroundColor="yellow"; // if false, change colors and return false
field.style.color="red";
return false;
}
else {
field.style.backgroundColor="white"; // if true, change colors and return true
field.style.color="black";
return true;
}
}
Maybe
var trueOrfalse = reg2.test(field)
should be
var trueOrfalse = reg2.test(field.value)
Added:
Also, remember that you don't have to compare to true or false when evaluating in a boolean context. (Use the value itself or the negation). And it is better to name variables after their meaning, not "trueorfalse" Here's my re-write:
if (!testPattern(phone1, /^\d{3}$/)) { // checking phone length
valid = false;
}
if (!testPattern(phone2, /^\d{3}$/)) {
valid = false;
}
if (!testPattern(phone3, /^\d{4}$/)) {
valid = false;
}
function testPattern(field, reg2) {
var good = reg2.test(field.value);
if (good) {
field.style.backgroundColor="white"; // if good, change colors
field.style.color="black";
}
else {
field.style.backgroundColor="yellow"; // if bad, change colors
field.style.color="red";
}
return(good);
}
Not an actual answer to your question, since there's nothing inherently wrong with the snippets you posted, but this was too large for a comment.
Your code is really redundant!
You could express the whole first part as:
valid = testPattern(phone1, /^\d{3}$/) &&
testPattern(phone2, /^\d{3}$/) &&
testPattern(phone3, /^\d{4}$/)
And the function code as:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
if (test_result) {
field.style.backgroundColor = "white";
field.style.color = "black";
} else {
field.style.backgroundColor = "yellow";
field.style.color = "red";
}
return test_result;
}
Or even more concise:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
field.style.backgroundColor = test_result ? "white" : "yellow";
field.style.color = test_result ? "black" : "red";
return test_result;
}
Isn't that much easier to read?

Categories

Resources