Recursive loop in javascript with increment based on a link click - javascript

I'm populating form fields and prompting the user through them using a javascript recursive loop.
I'm having a problem with the recursion not working as expected.
I have a recursive loop that prompts a user through 6 input fields.
field1 and field2 populate as expected, but field3 and field4 fire off together and field5 and field6 fire off together.
I think it has something to do with global vs. local variables or possibly scoping inside the loop() function, but I'm struggling with figuring it out.
JSFiddle: http://jsfiddle.net/9QtDw/5/
Click on the "Save Data" button to fire off the loop and you can see the loop() function iterate with confirm popups guiding the user.
Any help pointing me in the right direction is greatly appreciated.
var x = 0;
var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]
function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in the fieldnames array
return;
}
confirm( 'Highlight the ' + fieldnames[i] + ' text' );
console.log("outside on click function i=" + i);
//function to be called when button is clicked
$("#text-submit").on("click", function(){
//fieldinfo = $("#cs-ResultText").text();
$('#' + fieldnames[i] + '').val('this is where i = ' + i);
// increment i and recall the loop function for the next field
if(i >= fieldnames.length - 1 ){ return false; }
i=i+1;
console.log(i);
console.log("inside on click function i=" + i);
return loop(i); // the recusive call back into the loop
});
return false;
}
// only fire off the loop call on the first run through, after that it's called on #text-submit click
if( x === 0 ){
loop(x);
}

try this instead:
var x = 0;
var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]
function loop(y) {
i = y;
if (i >= fieldnames.length) { return; }
confirm( 'Highlight the ' + fieldnames[i] + ' text' );
$('#' + fieldnames[i] + '').val('this is where i = ' + i);
return false;
}
$("#text-submit").on("click", function(e){
e.preventDefault();
if(i >= fieldnames.length - 1 ){ return false; }
i=i+1;
loop(i);
});
if( x === 0 ){
loop(x);
}
working fiddle here: http://jsfiddle.net/9QtDw/6/
I hope it helps.

You are not looping!!!
ya just loop for 2 time
you should change your loop function like this:
function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in the fieldnames array
return;
else
$("#text-submit").trigger('click')
}

Related

How to auto increment a variable after a condition is true for a different variable in javascript

I am trying to develop a mini browser infinite clicker idle game.
My problem is that i am trying to auto increment a variable every second by 1, only if a certain condition is true.
Here is the code i have:
var income = 0;
var a = 0;
function buttonOne(){
document.getElementById
("myElementName").innerHTML = " some text " + a++;
}
Now the problem i get is that i want the variable income to auto increment only when variable a has a value more than 1.
I have tried the following:
If( a >= 1 ){
Window.setInterval(
document.getElementById
("elementThatIChose").innerHTML = " some text " +
income++;
},1000);
Now when i use the above code it does not do anything and it negativly affect my onclick function for buttonOne.
Does anyone know how to make variable income auto increment after variable a is a certain value. I have tried all other loops and nothing is working.
You have to increment it inside the callback:
window.setInterval(function() {
if( a >= 1 ){
document.getElementById("elementThatIChose").innerHTML = " some text " + (income++);
}
},1000);
You can use prefix increment scoped with parenthesis, like this
var income = 0;
var a = 0;
function buttonOne() {
document.getElementById("myElementName").innerHTML = " some text " + (++a);
}
window.setInterval(function() {
if (a > 0)
document.getElementById("elementThatIChose").innerHTML = " some text " + (++income);
}, 1000)
However it's easier to read the code by incrementing the variables outside of the assignment expression like this
function buttonOne() {
a++;
document.getElementById("myElementName").innerHTML = " some text " + a;
}
window.setInterval(function() {
if (a > 0) {
income++;
document.getElementById("elementThatIChose").innerHTML = " some text " + income;
}
}, 1000)

Javascript counter++ skips counting

I am building a simple JS game but ++ keeps on adding up for no reason.
Here is the code:
var cities = ["Atlanta","Chicago","Honolulu","Houston","Nashville","Orlando","Philadelphia","Phoenix","Portland","Seattle"],
c = Math.floor((Math.random() * 10)),
city = cities[c].toUpperCase(),
cityArr = city.split(""),
length = city.length,
guess = 0,
$prompt = $('#prompt'),
x, //letter guess
i;
function randomCity() {
var $showCity = document.getElementById("showCity"), //ul
newLi,
letter;//each letter of city
for(i=0; i<cityArr.length; i++){
newLi = document.createElement("li");
$showCity.appendChild(newLi);
letter = document.createTextNode(cityArr[i]);
newLi.appendChild(letter);
}
$("#showCity li").css("color", "#fff");
}//end randomCity()
function play() {
if(guess == 6){
$("#alphabet").css("visibility", "hidden");
ending();
} else {
$prompt.fadeIn("slow").text("Guess a letter: ");
guessLetter();
}
} // end play function
function guessLetter() {
var showLetter;
guess++
console.log(guess); //SHOWS THE COUNTER ADDING UP CONTINUOUSLY AFTER 2
$("#alphabet li").on('click', function () {
$(this).css("visibility", "hidden");
x = this.id;
if (city.indexOf(x) == -1) {
$prompt.fadeIn("slow").text("No letter " + x);
setTimeout(play, 1500);
} else {
for (i = 0; i < length; i++) {
if (city[i] == x) {
$prompt.fadeIn("slow").text("There is letter " + x + "!");
showLetter = "#showCity li:nth-child("+(i+1)+")";
$(showLetter).css("color", "#0F9ED8");
}
} //for loop
setTimeout(play, 1500);
} //else
});
}
function ending(){ //STILL IN PROGRESS
var guessWord,
finalOutput;
$prompt.fadeIn("slow").text("What is the word? ");
//guessWord = word from input
finalOutput = (guessWord == city) ? "That is correct!" : "Sorry, that is wrong.";
$prompt.fadeIn("slow").text(finalOutput);
}
$(document).ready(function(){
$("#start").on('click', function() {
$(this).hide();
randomCity();
console.log(city);
$("#alphabet").css("visibility", "visible");
play();
});
}); // end ready
variable guess (the counter) has value of 4 after clicking the 2nd element, and has a value of 6 after clicking the 3rd element. I moved the var guess in different parts of my code but it is still doing that. This is very weird!
By doing
$("#alphabet li").on('click', function () { /* ... */}`
you're binding a new click handler every time the guessLetter() function gets executed. Multiple click handlers will call the play() function which in turn calls the guessLetter() function again, resulting in guess being incremented multiple times.
Bind the click handler only once.
You are attaching a new click handler to your list items every time the guessLetter function is called.
To fix it, you could move everything in guessLetter which occurs after your console.log call into the $(document).ready callback function.

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Unable to get proper element count on drop

I have noticed at several attempts to get a count of dropped elements it always returns one less than the number found, but if I try the same command via Chromes console I get the propper response.
I assume the DOM is not updated when this script runs so I threw a timeout/try again mechanism but still with no avail. What am I missing?
Expected Result size = 10
Actual Result size = 9
Code
var asmCount = 0;
function storeValues(values, tryNumber){
var size = values.length,
tryNumber = (!isNaN(tryNumber)) ? tryNumber : 1
;
console.log('full boat:' + size + ', try #'+ tryNumber + ' ' + typeof(tryNumber));
if(tryNumber > 60){
console.log('too many tries');
return;
}
if(size < 10){
console.log('missing entries');
tryNumber = tryNumber + 1;
setTimeout(storeValues($('.asm-ranking .receiver .asm-value'), tryNumber) , 500);
} else if(size > 10){
console.log('too many entries, something broke');
} else {
console.log('just right, lets do this shit.');
//$.each(values, function(k,v){ console.log($(v).data('id'));});
}
}
$('.asm-ranking .receiver').droppable({
drop: function(event,ui){
var _self = this,
receiverCount = $('.asm-ranking .receiver li').length
;
//console.log('event',event);
//console.log('ui', ui);
asmCount++;
console.log(asmCount + ' / ' + receiverCount);
if(receiverCount == asmCount){
storeValues($('.asm-ranking .receiver .asm-value'), 1); // give DOM time to catch up, then store
}
}
});
for some reason when I wrapped my jQuery notation in with document ready
$(document).ready(function{ ... })
it works as expected.

locaStorage and javascript loop

I have a problem with my little app,
You can see it here : http://jsfiddle.net/47bV8/
My problem is : I enter some notes then when I "clear All", and i re-enter a note,
the console returns me lsReturn == null on the refresh .
I understand Why but can't see how to solve the problem.
In fact the value of my 'var i' is not 0 after clear all (it's value is the last note i've entered so 5 if i've entered 5 notes), so when i re enter a note it's task-6, so on the refresh my first loop fails...
I tried to set var i = 0 after the localstorage.clear but it doesn't worK...
jQuery(document).ready(function() {
// Initial loading of tasks
var i = 0;
// clear All
jQuery('.clear').on('click',function(e){
e.preventDefault();
jQuery('#tasks li').remove();
localStorage.clear();
jQuery(this).data('erase', true);
});
if(localStorage.length){
for( i = 0; i < localStorage.length; i++){
var lsReturn = JSON.parse(localStorage.getItem('task-'+i));
if (lsReturn == null){ // HERE IS THE PROBLEM
var b = 0; //
}else{
jQuery("#tasks").append("<li id='task-"+i+"'>" + lsReturn.text + " <a href='#'>Delete</a></li>");
jQuery('#tasks li#task-'+i+'').css('background-color', lsReturn.color );
}
}
}else{
jQuery('header').after("<p class='error'>no messages</p>");
}
// ----------------- ADD A TASK ----------------------//
jQuery("#tasks-form").submit(function() {
if (jQuery("#task").val() != "" ) {
jQuery('#task').attr('placeholder', "Enter a note")
var text = jQuery("#task").val();
var color = jQuery('#color').val();
var allNotes = {};
var note = {};
note.text = text;
note.color = color;
allNotes['task-'+i] = note;
var lsStore = JSON.stringify(allNotes['task-'+i ]);
localStorage.setItem( "task-"+i, lsStore);
var lsStoreReturn = JSON.parse(localStorage.getItem("task-"+i, lsStore));
jQuery("#tasks").append("<li id='task-"+i+"'>"+ lsStoreReturn.text +"<a href='#'>Delete</a></li>");
jQuery('#tasks li#task-'+i+'').css('background-color', lsStoreReturn.color );
jQuery("#task").val("");
i++;
}else{
jQuery('#task').attr('placeholder', "nothing in it !")
}
return false;
});
// ----------------- REMOVE A TASK ----------------------//
jQuery("#tasks li a").live("click", function(e) {
e.preventDefault();
localStorage.removeItem(jQuery(this).parent().attr("id"));
jQuery(this).parent().remove();
// PROBLEM solved : if I remove a task #2 in a list of 4 item for example, if i refresh the list become 0, 1, 3, 4,
// so the locastorage loop doesn't find the item 2
for(i=0; i<localStorage.length; i++) { // SO I check my locastorage
if(localStorage.getItem("task-"+i) == null) { // If the task 4 doesn't exist
localStorage.setItem("task-"+i, localStorage.getItem('task-' + (i+1)));
// I do : create task-4
// and give him the value of task 5
localStorage.removeItem('task-'+ (i+1) );
// the i remove task 5
// so the loop wiil not find task 5 and give him the value of task 6 etc..
}
}
});
});​
Reset your i variable in the following way
jQuery('.clear').on('click',function(e) {
e.preventDefault();
jQuery('#tasks li').remove();
localStorage.clear();
jQuery(this).data('erase', true);
// Need to reset the index counter here.
i = 0;
});
Here is an updated/working fiddle.

Categories