For loop using jQuery and JavaScript - javascript

I'm trying to do a simple for loop in JavaScript/jQuery
every time I click NEXT, I want the I to increment once.
But it is not working. When I press next, nothing happens.
<script>
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
//start increment with 0, until it is reach 5, and increment by 1
for (var i=0; i < 5 ;i++)
{
//when I click next field, run this function
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
var fields_box = '#field_'+[i];
show_form_field(fields_box)
})
}
});
</script>

You do not need the for loop. Just declare var i outside click function and increment it inside the function.
//function to show form
function show_form_field(product_field) {
$(product_field).show("slow");
}
$(document).ready(function () {
var i = 0; // declaring i
$("#next_field").click(function () {
if (i <= 5) { // Checking whether i has reached value 5
var fields_box = '#field_' + i;
show_form_field(fields_box);
i++; // incrementing value of i
}else{
return false; // do what you want if i has reached 5
}
});
});

You should declare variable i document wide, not inside the click handler.
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
var i=0;
$("#next_field").click(function(){
var fields_box = '#field_'+ i++ ;
show_form_field(fields_box)
})
});

Call $("#next_field").click just one time, and in the click function, increase i every time.
$(document).ready(function() {
var i = 0;
$("#next_field").click(function() {
if (i >= 5) {
//the last one, no more next
return;
}
show_form_field('#field_' + (i++));
});
});

try this
$(document).ready(function(){
//start increment with 0, untill it is reach 5, and increment by 1
var i = 0;
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
if(i<5)
{
var fields_box = '#field_'+i;
show_form_field(fields_box);
i+=1;
}
else
{
return;
}
});
});

Related

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.

setInterval increment index mystery

I am bangging my head against a wall, I cant figure out what is happening when I try increment my index value from outside my function.
So I starts off as 0, great! Each loop through i gets i +1 (this all seems great) ... but when I click #sliderNext you will see I dont add to the i value, yet it still increments the i value (why???) That means when I click prev I have to decrease the value by 2 instead of i-- (again, why?) ... am I being thick and not seeing something obvious?
Perhaps a better way to add prev + next (one that does not stop the setinterval completely)
$.when( loadImages() ).done(function(a1){
var i = 0;
var numberOfImgs = imgArr.length;
function sliderRotate(passi){
$('#autoSlider').html(imgArr[i]); //show with current i index
i++; //it should increment AFTER image has shown
if (i >= numberOfImgs || i < 0){ i = 0; }
}
sliderRotate();
intervalID = setInterval(sliderRotate, 3000);
//prev + next clicks
$('#sliderNext').on( 'click' , function(){
clearTimeout(intervalID);
//x = i + 1;
sliderRotate();
});
$('#sliderPrev').on( 'click' , function(){
clearTimeout(intervalID);
if ( i === 0 ){ i = imgArr.length -2; } //this only kind of works if I click twice on the first image
else{i = i - 2; }
sliderRotate();
});
});// end of when
Here is a snippet example:
$(document).ready(function(){
var imgArr = [
'<img src="http://www.freedigitalphotos.net/images/img/homepage/87357.jpg">',
'<img src="http://assets.barcroftmedia.com.s3-website-eu-west-1.amazonaws.com/assets/images/recent-images-11.jpg">',
'<img src="https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/pia20645_main.jpg?itok=dLn7SngD">',
'<img src="https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/pia18368-1041.jpg?itok=Fkc2j_kw">',
'<img src="http://www.irishtimes.com/polopoly_fs/1.2527148.1454955520!/image/image.jpg_gen/derivatives/landscape_685/image.jpg">',
'<img src="http://www.gettyimages.in/gi-resources/images/Homepage/Hero/US/Feb2016/video-481880130.jpg">'
];
var i = 0;
var numberOfImgs = imgArr.length;
function sliderRotate(passi){
$('#autoSlider').html(imgArr[i]);
i++; //should increment here, not before???
if (i >= numberOfImgs || i < 0){ i = 0; }
}
sliderRotate();
intervalID = setInterval(sliderRotate, 3000);
//prev + next clicks
$('#sliderNext').on( 'click' , function(){
clearTimeout(intervalID);
//x = i + 1;
sliderRotate();
});
$('#sliderPrev').on( 'click' , function(){
clearTimeout(intervalID);
if ( i === 0 ){ i = imgArr.length -2; } //kindah works, but still buggy
else{i = i - 2; }
sliderRotate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderContainer">
<div id="sliderNext">Next</div><br><br><br>
<div id="sliderPrev">Prev</div>
<div id="autoSlider"></div>
</div>
Initial value of i is 0. sliderRotate function renders the first image (at index 0) and increments i by 1. In the next execution of this function the second image (at index 1) will be shown and i will have a value 2.
Now, you want to get back to the previous image (at index 0). But value of i is 2. You have to show image at index i - 2.
You are calling sliderRotate():
$('#sliderNext').on( 'click' , function(){
clearTimeout(intervalID);
//x = i + 1;
**sliderRotate();**
});
And that will increment it by 1:
function sliderRotate(passi){
$('#autoSlider').html(imgArr[i]);
i++; //should increment here, not before???
if (i >= numberOfImgs || i < 0){ i = 0; }
}
Same for "prev", you are adding 1 when you call sliderRotate(), that is why you need to subtract 2.
Here is a working example with your code: https://jsfiddle.net/owbL084z/2/

Show elements of array one by one - Jquery

So I have a button on which I want to display each element of my array for a few seconds. This is my html code:
<button class="btn" id="random">Start</button>
I have made an array with jQuery that I want to use to change the buttons text:
$(document).ready(function() {
$("#random").on("click", loop);
});
var array = ["el1","el2","el3"];
function loop() {
for (i = 0; i < array.length; i++) {
$("#random").html(array[i]);
}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}
The for loop is supposed to do what I want but I can't find a way to delay the speed, it always just shows the last line of code. When I try setTimeout or something it just looks like it skips the for loop.
My proposal is to use IIFE and delay:
var array = ["el1","el2","el3", "Start"];
function loop(){
for (i = 0; i < array.length; i++){
(function(i) {
$("#random").delay(1000).queue(function () {
$(this).html(array[i]);
$(this).dequeue();
});
})(i);
}
}
$(function () {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>
Basically, a for loop will not help you. It runs with the max speed it can. And delaying it would do no good in js (you would just freeze the browser). Instead, you can just make a function that will execute itself with a delay. Kinda recursion, but not entirely. Below would make the trick.
https://jsfiddle.net/7dryshay/
$(document).ready(function() {
$("#random").on("click", function (event) {
// texts to cycle
var arr = ["el1","el2","el3"];
// get the button elem (we need it in this scope)
var $el = $(event.target);
// iteation function (kinda recursive)
var iter = function () {
// no more stuff to display
if (arr.length === 0) return;
// get top of the array and set it on button
$el.text(arr.shift());
// proceed to next iteration
setTimeout(iter, 500);
}
// start first iteration
iter();
});
});
Use setInterval() and clearInterval()
$(document).ready(
function() {
$("#random").on("click", loop);
}
);
var array = ["el1", "el2", "el3"];
var int;
function loop() {
var i = 0; // variable for array index
int && clearInterval(int); // clear any previous interval
int = setInterval(function() { //store interval reference for clearing
if (i == array.length) clearInterval(int); // clear interval if reached the last index
$("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>
UPDATE : If you need to implement it using for loop and setTimeout() then do something like this
var array = ["el1", "el2", "el3", "Start"];
function loop() {
for (i = 0; i < array.length; i++) {
(function(i) {
setTimeout(function() {
$("#random").html(array[i]);
}, i * 1000);
})(i);
}
}
$(function() {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>

Update atrribute value on click in dynamic table cell span

How do I make the Up buttons to update the attribute value? When I increase the count fx to 5 and then decrease it with Down buttons to 2, and then increase it again, it does not increase from the current value of attr value wich is 2 but continues from 5. I just don't know how to update it after Down button has been clicked. DEMO
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).each(function(index, element) {
var count= $(element).closest('tr').find('.times').attr('data-myval');
$(element).click(function() {
count++;
$(element).closest('tr').find('.times').attr('data-myval', count);
$(element).closest('tr').find('.times').text(count +' x');
});
});
$(minus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr')
.find('.times').attr('data- myval');
count--;
parseInt($(element).closest('tr')
.find('.times').attr('data-myval',count))
$(element).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(element).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
});
Please set the countinside the click event for the up button:
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr').find('.times').attr('data-myval');
count++;
$(element).closest('tr').find('.times').attr('data-myval', count);
$(element).closest('tr').find('.times').text(count +' x');
});
});
$(minus).each(function(index, element) {
$(element).click(function() {
var count= $(element).closest('tr')
.find('.times').attr('data- myval');
count--;
parseInt($(element).closest('tr')
.find('.times').attr('data-myval',count))
$(element).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(element).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
});
I hope that helps :D
I refactored your code to avoid putting click handlers inside of a loop. jQuery lets you listen to click events on a per class basis without expressly defining each one.
The contents of each function is largely unchanged, I just saved the elements we need to look up in variables to avoid looking them up repeatedly.
Your problem in the code posted was count being set outside of the click handler. That logic has been moved inside of the .up click handler.
Fiddle
Javascript
$(function() {
$('.up').on('click', function(){
var count = $(this).closest('tr').find('.times');
var curVal = Number(count.attr('data-myval'));
count.attr('data-myval', curVal + 1);
count.text(curVal + 1 + ' x');
})
$('.down').on('click', function(){
var count = $(this).closest('tr').find('.times');
var curVal = Number(count.attr('data-myval'));
curVal--;
count.attr('data-myval', curVal);
count.text(curVal + ' x');
if (curVal < 2) {
count.text('');
}
if (curVal < 1) {
$(this).parents('tr').remove();
}
})
});
I'm guessing you are setting the count outside of the onclick function
var count= $(element).closest('tr').find('.times').attr('data-myval');
So the count may hold the previous value that was set when the last up was pressed.
grab the value first in count variable then increment i update your jsfiddle, i hope its helpful for you
var count = $(element).closest('tr').find('.times').attr('data-myval');
count++;
https://jsfiddle.net/j9vnbcf0/13/
You just don't need to go through for .each function for each plus/minus btns, simply call .click function on them directly, it works that way-
JS-
$(function() {
var plus = $('.up');
var minus = $('.down');
$(plus).click(function() {
var count= $(this).closest('tr').find('.times').attr('data-myval');
count++;
// console.log(count);
$(this).closest('tr').find('.times').attr('data-myval', count);
$(this).closest('tr').find('.times').text(count +' x');
});
$(minus).click(function() {
var count= $(this).closest('tr').find('.times').attr('data-myval');
count--;
parseInt($(this).closest('tr').find('.times').attr('data-myval',count))
$(this).closest('tr').find('.times').text(count +' x');
if (count<2) {
$(this).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
});
Here goes the updated link-
https://jsfiddle.net/j9vnbcf0/14/

setInterval won't get out of loop

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);
Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

Categories