How do I use repeated value in innerhtml? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code but it's not repeat
it increase the value but don't get to the initial value 0
please help
i=0;
function loading()
{
text=["Loading.","Loading..","Loading...","Loading...."];
window.setInterval(wr(),500)
}
function wr()
{
if(i<4)
{
wr='document.getElementById("text").innerHTML=text[i]';
alert(i);
}
else
i=0;
return wr;
}

Your code is way to complicated. Define a simple function which you pass to setInterval and make sure you increase the counter variable:
var i = 0; // initialize counter
var textElement = document.getElementById("text");
setInterval(function() {
i = i % 4; // make sure `i` is at max 3 and reset to 0
var text = 'Loading';
for (var j = i; j--; ) {
text += '.'; // add the correct number of periods
}
textElement.innerHTML = text; // set text
i++; // increase counter
}, 500);
DEMO

Here's a slight modification of a similar answer I gave a while back.
var i = 0;
setInterval(function() {
i = ++i % 4;
document.getElementById('text').innerHTML = "Loading"+Array(i+1).join(".");
}, 500);

Related

Unexpected behaviour with for in a nodelist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a nodelist with 30 divs and I need to include 1 div every 4 divs but the var 'c' does not change and stack all the divs in the position[6].
for (i = 0; i < 8; i++) {
var pub = "pub-retangulo-";
var c = 2;
c += 4;
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
}
You are redeclaring your c variable at each iteration. That is why is it stuck at 6. You need to move this assignation outside your loop
var pub = "pub-retangulo-";
var c = 2;
for (i = 0; i < 8; i++) {
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
c += 4;
}
I've also moved your c+=4 at the end of the loop, this will cause the loop to execute at c = 2 the first time rather than c = 6
As Barmar said, you might not need a variable at all in this case. You are incrementing by four each time, so you could replace your c variable with 2 (initial value) + i(current iteration index) * 4 (increment ratio).
P.S. This code is UNTESTED, please don't just copy and paste it expecting everything to work perfectly. Try to understand it and apply it to your own context.

JS loop producing no result [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Trying to create an array with a loop and then sum all the contents of the array and put the result as the contents of a DIV but when I run the fiddle I get no result and jshint says everything is well formed.
var begin = 500000;
var stop = 999999;
var arrInt = [];
// Create an array worth summing
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
// Sum all ints in an array
var IntSum = function (ManyInts) {
var i = arr.length; while (i--) {
return;
}
};
var example = document.getElementById("example").innerHTML;
example=IntSum(arrInt);
<div id="example"></div>
http://jsfiddle.net/7b8rqme5/
At no point do you call CreateArray. You call your other function, IntSum, which does precisely nothing. Also, you create a variable example and assign a dom element to it, then you immediately overwrite it with a (noop) function result. There are additional issues with your code as well.
My advice: slow down, determine what it is you need to accomplish, and take it step by step.
I think this is what you wanted. But not really sure what you are trying to do here.
var begin = 500000;
var stop = 999999;
var arrInt = [];
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
var IntSum = function (ManyInts) {
var sum = 0
var i = ManyInts.length; while (i--) {
sum += ManyInts[i];
}
return sum;
};
var example = document.getElementById("example").innerHTML;
CreateArray(begin, stop);
var saic=IntSum(arrInt);
document.getElementById("example").innerHTML = saic
http://jsfiddle.net/wpnkL6k2/

Randomly selecting a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am creating just a little test game type thing, and for part of it, I need a function to be randomly selected.
I have 2 altogether, and I just need to create maybe a 'random generator' somehow, which I can call, and it runs one of the 2 functions.
function function1() {
........code.........
}
function function2() {
........code.........
}
function generator() {
...random function selector...
}
Maybe something like that ^
Thanks in advance!
Yes, you can do that.
var myFuncArr = ["function1","function2"];
function generator(){
window[myFuncArr[Math.random() * (myFuncArr.length - 0) + 0]]();
}
JavaScript has an eval function that evaluates a string and executes it as code:
function generator(){
min = 1;
max = 5;
random = Math.floor(Math.random() * (max - min + 1)) + min;
param = "myParam";
eval("function"+random+"('"+param+"')");
}
Do you expecting like this
function method1(){
document.getElementById("sampleDiv").style.color = "red";
}
function method2(){
document.getElementById("sampleDiv").style.color = "yellow";
}
function method3(){
document.getElementById("sampleDiv").style.color = "orange";
}
function generator(id) {
eval("method"+id+"()")
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
setInterval(function(){generator(randomIntFromInterval(1,3))},3000);
Demo:
http://jsfiddle.net/hcmY9/3/

Obtaining a DOM element and adding event listener to it dynamically [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a function where I am dynamically trying to access a DOM element by passing it's id to a function and then adding an event listener to it,this code works perfectly outside a function but it does not work here.The function looks like this:
var count = 0;
function disableOnCheck(radioId, textBoxId) {
var a = document.getElementById(radioId);
var atext = document.getElementByID(textBoxId)
alert(a.value);
a.addEventListener('click', function (event) {
alert(count);
count++;
if (count === 2) {
a.checked = false;
atext.disabled = false;
count = 0;
return;
}
alert(a.value);
atext.disabled = true;
});
};
I run this using:
disableOnCheck('a','atest');
Also here is a fiddle that I created http://jsfiddle.net/vamsiampolu/vKkUP/2/
JavaScript is case-sensitive. It should be :
var atext = document.getElementById(textBoxId);
instead of
var atext = document.getElementByID(textBoxId);
You would have seen an error (Uncaught TypeError: Object # has no method 'getElementByID') in your console if you try to use it.
Update:
You are not getting what you want because you pass in the wrong variable in your
disableOnCheck function.
You have disableOnCheck('a', 'atest');
when it should be disableOnCheck('a', 'atext');
See Fiddle
change document.getElementByID to document.getElementById
First you are attempting to get the element Id by wrong methond, javascript is a case sensitive language
HERE IS A WORKING CODE:
var count = 0;
function disableOnCheck(radioId, textBoxId) {
var a = document.getElementById(''+radioId);
var atext = document.getElementById(''+textBoxId); // you were using getElementByID which is wrong
alert(a.value);;
a.addEventListener('click', function (event) {
alert(count);
count++;
if (count === 2) {
a.checked = false;
atext.disabled = false;
count = 0;
return;
}
alert(a.value);
atext.disabled = true;
});
};
disableOnCheck('a','atext'); // HERE you were using `atest` which is not a element id it's `atext`
The fiddle link is here.

Can i make my code shorter? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I have many functions for calculating some stats , and i need to recheck the value's every time but that is extra code and make's it harder to read , can i store the variable assignment in another function:
function MC () {
var check=document.getElementById('check').checked;
var ea=Number(document.form.ea.value),
ed=Number(document.form.ed.value),
pa=Number(document.form.pa.value),
pd=Number(document.form.pd.value);
var hpSum = 0,spSum=0,eaSum=0,edSum=0,pdSum=0,paSum=0;
if(check){
eaSum = ea + 11;
edSum = ed + 17;
pdSum = pd + 17;
paSum = pa + 11;
} else {
eaSum = ea - 11;
edSum = ed - 17;
pdSum = pd - 17;
paSum = pa - 11;
}
document.form.ea.value=eaSum;
document.form.ed.value=edSum;
document.form.pa.value=paSum;
document.form.pd.value=pdSum;
};
NOTE:I am speaking for the variables:ea,ed,pa,pd and sum variables.
You could try building an object of parameters:
function MC() {
var check = document.getElementById('check').checked,
keys = {
"ea":11,
"ed":17,
"pd":17,
"pa":11
}, i;
for( i in keys) { if( keys.hasOwnProperty(i)) {
document.form[i].value = +document.form[i].value + (check ? keys[i] : -keys[i]);
}}
}
Note that +somevar is a cheap shortcut for parseFloat(somevar). Number(somevar) is NOT the same as it creates a wrapper object that may interfere with comparisons if you add any in later.
I'd go with your own code, condensed a bit. Assuming form is the name of a form, it would take more code to keep track which inputs have changed than to read them.
function MC () {
var f= document.form,
v= document.getElementById('check').checked? [11, 17]:[-11, -17];
f.ea.value= Number(f.ea.value)+v[0];
f.ed.value= Number(f.ed.value)+v[1];
f.pa.value= Number(f.pa.value)+v[0];
f.pd.value= Number(f.pd.value)+v[1];
}

Categories