How to increment a number within a variable name in jQuery - javascript

I have this javascript for loop:
for (var i=1; i <= 2; i++) {
$(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}
I need to increment the number at the end of a jQuery variable name so that I get this:
$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);
I have tried using
$.afterglowplayer+i.toggle(this);
and
$.afterglowplayer+"+i+".toggle(this);
But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

You can use the let keyword
for (let i=1; i <= 2; i++) {
$(".afterglowplayer"+i).click(function () {
$('.afterglowplayer'+i).toggle(this);
return false;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='afterglowplayer1'>Foo</div>
<div class='afterglowplayer2'>Bar</div>

Read up on JavaScript closures.
for (var i=1; i <= 2; i++) {
(function(n) {
$('.afterglowplayer'+n).click(function () {
$('.afterglowplayer'+n).toggle(this); return false;
});
})(i);
}

$['afterglowplayer'+i].toggle(this);

Related

JS setTimeout() function

i just started to learn JS. I want to change my span tag's position with respect to time with JS setTimeout function. But it did not worked with this code. What am i doing wrong ?
function myFunction2() {
var j = 0;
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
var i = 0;
while (i <= 200) {
setTimeout(myFunction2, 20);
i++;
}
You need to declare j outside the function. Otherwise, you're always setting it to 0 every time the function is called.
Also, you're running all instances of the function at the same time, 20 ms after the loop. You should multiply the timeout by the loop index:
Full demo:
var j = 0;
function myFunction2() {
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
var i = 0;
while (i <= 200) {
setTimeout(myFunction2, 20 * i);
i++;
}
}
<span id="demo" style="position:absolute;left:0px;">Bu benim ilk paragrafım.</span><br> <button type="button" onclick="myFunction();">Try</button>
Or you could use setInterval() to run it repeatedly automatically.
function myFunction() {
var j = 0;
var int = setInterval(function() {
if (j > 200) {
clearInterval(int);
} else {
document.getElementById("demo").style.left = j + "px";
j++;
}
}, 20);
}
<span id="demo" style="position:absolute;left:0px;">Bu benim ilk paragrafım.</span><br> <button type="button" onclick="myFunction();">Try</button>
It seems like you are declare the J variable inside the function and set it to 0 every time. So every time when you call the function you're calling the timeout on same interval. And My solution is set the J Out side the function like a global variable and then try it.
var j = 0;
function myFunction2() {
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
for (var i = 0; i <= 200; i++) {
setTimeout(myFunction2, 20 * i);
}
}
It is not working because whenever you are calling myFunction2(), variable j is initialized with 0 again and technically you are assigning 0px to demo. So that's why it's not shifting.
As said , you need to declare j as a variable outside the function itself , then you eventually test it within the function .
I would use for (){} instead while () {}
here is another example :
let j;// declare j
function myFunction2() {
if (!j) {// has j already a value ?
j = 0;
}
document.getElementById("demo").style.left = j + "px";
j++; // now it has a value, it can be incremented from here anytime the function is called
}
function myFunction() {
for (let i = 0; i <= 200; i++) {
setTimeout(myFunction2, i * 20);// increment settimeout for each loop
}
}
#demo {
position: relative;
}
<div id="demo">test demo</div>
<button onclick="myFunction()">test myFunction</button>
Now, every time you call the function it increments the position of 200px away from lft. 1 click = 200px , 2click = 400px ;
Have fun coding ;)

self executing anonymous click function in for loop

I need a click function in a for loop, so every id element is clickable. But I also need the i in the click function, that's why I thought a self executing anonymous function would be the best way to do so. But for some reason this is not working, maybe because the click function doesn't allow me to forward a parameter? What have I done wrong?
for (var i = 0; i < countItems; i++) {
$("#item-" + i).click(function(idx) {
alert(idx);
})(i)
}
The self executing function must return a function:
for (var i = 0; i < countItems; i++) {
$("#item-" + i).click(function(indx){
return function(){ //must return a function
alert(indx);
}
}(i));
}
JS Fiddle: http://jsfiddle.net/HuHXr/
As a side note, using bind() javascript method:
for (var i = 0; i < countItems; i++) {
$("#item-" + i).click(function(indx){
alert(indx);
}.bind($("#item-" + i)[0],i));
}
you can try something like this
for (var i = 0; i < countItems; i++) {
$("#item-" + i).click(clickFunctn);
}
function clickFunctn(obj){
var i=$(obj).attr('id').split('-')[1];
alert(i);
}
In this way you will optimize the code and your 'i' will be with you as well, and all items are clickable. And you are just binding one handler function.
for (var i = 0; i < countItems; i++) {
(function(i){
$("#item-" + i).click(function(idx) {
alert(idx);
});
})(i);
}
Also note that idx is the event object.
Fiddle: http://jsfiddle.net/2DRLx/

Capturing counter value in Javascript closure [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
The following code creates 10 elements under <body id="container" />. When i click on any element, I always see an alert with the value 10.
How can I get each alert to show the index of each element?
for (var i = 0; i < 10; ++i) {
var id = "#element_" + i;
$("#container").append('<p id="element_' + i + '">foo</p>');
$(id).click(function (e) {
alert(i);
});
}
You need either closure or simply use $.on() with data:
for (var i = 0; i < 10; ++i) {
var id = "#element_" + i;
$("#container").append('<p id="element_' + i + '">foo</p>');
$(id).on("click", i, function (e) { alert(e.data); });
}
Don't make functions inside for loops
for (var i = 0; i < 10; ++i) {
$("#container").append('<p id="element_' + i + '">foo</p>');
}
$("#container > p").click(function (e) {
var idNum = this.id.split('_')[1];
alert(idNum); // 0, 1, 2 ...
});
DEMO
need to create a private closure
for (var i = 0; i < 10; ++i) {
(function(idx){
var id = "#element_" + idx;
$("#container").append('<p id="element_' + idx + '">foo</p>');
$(id).click(function (e) {
alert(idx);
});
})(i)
}
Demo: Plunker

javascript function doesn't return any result

I've got a javascript function
<head>
<title>
Test
</title>
<script type="text/javascript">
function GetResult()
{
count = 0;
for(var i=0;i<10;i++){
for(var j=1;j<4;j++){
if (document.getElementById("label"+i+j).checked){
count +=1;
}
}
}
if (count!=10)
alert("Please answer all the questions");
else alert(count);
}
</script>
In the code there are a lot of radiobutton. ther look like
<input type="radio" name="q1" value="1" id="label01"/>
But my javascript function never shows alert.
The button that is supposed to call function is
<input type="button" value="Result" onclick="GetResult()"/>
Maybe button doesn't call GetResult?
To elaborate what Felix already said: Here is how you can check whether or not document.getElementById found the specified element (it will return null if it failed).
for (var i = 0; i < 10; i++) {
for (var j = 1; j < 4; j++) {
// Store the result in a local variable
var label = document.getElementById("label"+i+j);
// Include a check whether "null" got returned
if (label && label.checked) {
count +=1;
}
}
}
Try this:
function GetResult() {
var count = 0;
for (var i = 0; i < 10; i++){
for (var j = 1; j < 4; j++){
var label = document.getElementById("label" + i + j);
if (label && label.checked) {
count +=1;
}
}
}
if (count != 10) {
alert("Не все отвечено");
} else {
alert(count);
}
}
Added var to the count declaration.
Fixed up some general formatting.
The important bit: checked to see if document.getElementById() returned a value before checking that value's checked property.

How can I refresh a Div in javascript instead of the whole page?

The code below works and is good but I am going to place it into a DRUPAL page and I would like it to refresh the "DIV" instead of the whole page. Can someone help? Thanks!
document.write("<div class='box1'><center><h1>Telling Time Worksheets</h1></center><div class='box_number_holder'>")
var nums = [01,02,03,04,05,06,07,08,09,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0, j = array.length; i < j; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
document.write("<div class='box_numbers'><center>What Time is it?" + get_rand(nums) + "</center></div>");
}
Thanks!
Create a function that loops through all of your dynamically created div elements:
function refreshDivs() {
$('.box_numbers > center').each(function() {
$(this).html('What Time is it? ' + get_rand(nums));
});
}

Categories