Javascript for loop function array - javascript

I'm bit of a javascript newbie - I'm trying to make a function that when I click a button it will call out a single object out of my array, in order.

all it does is display "ee".
Of course, you are looping through the whole array and assigning each item to the innerHTML of that one element - and only the last one will stay there and show up.
What I want it to do is when I click the button to display "aa" then when I press it again to display "bb" instead of "aa" and so on.
Then you can't use a for-loop, but have to keep track of the counter manually and execute only one step per invocation of call.
var myArray = ["aa","bb","cc","dd","ee"];
var i=0;
function call() {
document.getElementById("placeDiv").innerHTML = myArray[i];
if (i < myArray.length-1)
i++;
else
i = 0; // restart, but you may as well show an error message
}

You want a closure.
var call = (function() {
var i = 0,
entries = ["aa", "bb", "cc", "dd", "ee"];
return function() {
return entries[i++ % entries.length];
};
})();
This keeps i and entries as private values, and returns a function that goes to the next entry in the list each time it is called.

Try this:-
You are looping through on each click and assigning value to the element innerHTML so it will always have only the last value from the array.
Demo
var myArray = ["aa","bb","cc","dd","ee"];
var i = 0;
function call(){
if(myArray.length <= i) i=0;
document.getElementById("placeDiv").innerHTML = myArray[i++];
}
if you don't want to use a global variable you can use this way too.
http://jsfiddle.net/zZ4Rm/
Use shift method on array to get the first item and then push it back tht end of the array for the cycle to happen.
var myArray = ["aa","bb","cc","dd","ee"];
function call(){
var val = myArray.shift();
myArray.push(val);
document.getElementById("placeDiv").innerHTML = val;
}

You are overwritting your placeDiv with innerHTML.
Try using:
function call(){
var yourVar= document.getElementById('placeDiv');
for (var i=0; i < myArray.length; i++) {
yourVar.innerHTML = yourVar.innerHTML + myArray[i];
}
}

<script type="text/javascript">
var myArray = ["aa","bb","cc","dd","ee"],
num=0;
function call() {
document.getElementById("placeDiv").innerHTML = myArray[num];
num++;
};
</script>
<button onclick="call()">Click!</button>
<div id = "placeDiv"></div>

Related

Javascript function to return page id's

I'm lookingfor a javascript function which returns the next value from an array on every function call.. I have created a script but i'm a little stuck now.. is there someone to help me?
My location:
resultLocation= "beugen";
This should be the identifier to get the correct array of id's. There will be more arrays with id''s for example resultLocation = "mill";
My array of Id's
var beugen = [];
beugen[0] = "140";
beugen[1] = "33";
beugen[2] = "121";
beugen[3] = "150";
beugen[4] = "52";
beugen[5] = "68";
beugen[6] = "70";
beugen[7] = "82";
beugen[8] = "15";
My function to return a value. (the next value should be shown on each call of getId (resultLoction)
getId = function(resultLocation) {
var arrayLength = beugen.length;
page = beugen;
for (var i = 0; i < arrayLength; i++) {
init_table(page[i]);
}
}
getId(resultLocation);
Now my function keeps on looping and calls the init_table(page[i]) as many times as there are id's in my array. It should get the first (140) on the first call of getId and the 2nd (33) on the next call, and if it reaches the end, it should start over again at the the top.
Maybe an array is not the best solution? I don't really know. Since there are multiple locations?
var i = -1;
function getId(){
i++;
if(i>beugen.length-1){
i=0;
}
init_table(beugen[i]);
return beugen[i];
}
or something like that might work if i understand the problem.

Using for loops

alert(cellvalue) shows three seperate pop ups:
-10-|Car|*POB*[,]-20-|Bus|*CLR*
-22-|Car|*CLR*[,]-5-|Bus|*POB*
-12-|Car|*POB*[,]-55-|Bus|*CLR*
I am then splitting these values and getting the three values I need as follows:-
var array = cellvalue.split("[,]");
var start_carStat = array[0].indexOf('*') + 1;
var end_carStat = array[0].indexOf('*',start_carStat);
var text_carStat = array[0].substring(start_carStat,end_carStat);
alert(text_carNum); shows '10', '22', '12'
var start_carNum2 = array[1].indexOf('-') + 1;
var end_carNum2 = array[1].indexOf('-',start_carNum2);
var text_carNum2 = array[1].substring(start_carNum2,end_carNum2);
alert(text_carNum); shows '20', '5', '55'
and then returning them as follows:-
return (text_carNum+', '+text_carNum2);
Since there could be upto 20 values in each array I am trying to use a for loop to achieve the same thing but I can't seem to get it to work.
At the moment I have:-
for(var i=0;i<array.length;i++){
var start_carNum = array[i].indexOf('-') + 1;
var end_carNum = array[i].indexOf('-',start_carNum);
var text_carNum = array[i].substring(start_carNum,end_carNum);
return (text_carNum);
}
with this alert(text_carNum) only shows '10','22','12'.
Any ideas on how I could get this to work the same way as above using for/each?
(hoping I have explained this clear enough)
You call return in your loop, so the function exits at the end of the first iteration. You have to concatenate all values in a variable :
var str_return = '';
for(var i=0;i<array.length;i++){
var start_carNum = array[i].indexOf('-') + 1;
var end_carNum = array[i].indexOf('-',start_carNum);
var text_carNum = array[i].substring(start_carNum,end_carNum);
str_return += '<span style="color:'+color+' !important;">'+text_carNum +'</span>';
}
return str_return;
BTW, notice that I change the last line : the style attribute was closed (double quote) just after the color, it has to be closed after !important.
return will always exit the function as soon as it is called. In your code, it is only able to reach array[0] before it leaves the loop.
A solution would be to append the values of array to another variable within your loop, and then return a value after the loop has finished.

Use array value as variable name

I need to use jQuery's keyup function to take the value from input html form elements and display said values in a div elsewhere.
The working code looks as follows:
$('#name').keyup(function() {
var name = $(this).val();
$('#name-in-document').html(name);
});
Since I have many identical instances of the above code block, I'd like to use a for loop to loop through an array of values. The catch is the name of the variable in the second line
var name = $(this).val();
would come from the array.
I have tried the following loop, which does not work because (as I understand it) a Javascript variable cannot be named an array value:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var inputsArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(inputsArray[i]);
})
};
So I have two questions:
Is it true that I cannot use the array values to create a variable in the for loop?
Is there an alternate way to accomplish the same thing (getting the variable names from the array) that might work?
I am just beginning JavaScript and really appreciate any insight. Thank you!
1. It is not true
2. You'll need to make a closure over the variable i or over the value from inputArray[i] and inside the event-bind the keyword this refers to the DOMNode witch triggers the event:
Read more absout closures here How do JavaScript closures work?
var inputsArray = ["phone", "name", "address"],
i = 0,
len = inputsArray.length;
for ( ; i < len; i ++ ) {
makeKeyupBind(inputsArray[i]);
}
function makeKeyupBind( value ) {
$("#" + value).on("keyup", function() {
$("#" + value + "-in-document").html( this.value );
});
}
That variable only exists within the scope of the function passed as a callback for the keyup event so I don't really see the need to give it a dynamic name; you could call it absolutely anything at all and not run into conflicts.
For the alternative approach, I would recommend giving #name (and his friends) a class name, e.g.
<input class="js-key-up" id="name" />
Then you can do away with the array and the for loop altogether. Also, adding new HTML elements would not require adding items to the array.
HTML
<input class="js-key-up" id="phone">
<input class="js-key-up" id="name">
<input class="js-key-up" id="address">
<p id="phone-in-document"></p>
<p id="name-in-document"></p>
<p id="address-in-document"></p>
JavaScript
​
$('.js-key-up').keyup(function (e) {
var id = $(this).attr('id');
$('#' + id + '-in-document').html($(this).val());
});​
I've created a jsfiddle with the code in.
Try this:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var valuesArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(valuesArray[i]);
})
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var htmlValue = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(htmlValue);
})
I think you don't need to name variable from array, do you?
You can build a selector straight from the array and skip the loop completely. Use the id of the current input to create the selector for the other element
var inputsArray = ["phone", "name", "address"];
$('#'+ inputsArray.join(',#') ).keyup(){
$('#'+this.id+"-in-document").html( $(this).val() );
})
This will create the selector:
$('#phone,#name,#address')
Above assumes that you are trying to find elements :
$("#phone-in-document").html(val);
$("#name-in-document").html(val);/* etc*/
#Wes Cossick: this line inside of the loop is wrong:
var valuesArray[i] = $(this).val();
if you want to do it that way declare the array before the loop. that is problem of OP
#diana: if i understand you correct, you want to add a dynamic keyup handler to every item in the array? if it is that way, that code should do it (dont reassign items in the array!) the trick is to create a closure (code is untested).
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
(function(item) {
$("#"+item).keyup(function() {
$("#"+item+"-in-document").html($(this).val());
});
})(inputsArray[i]);
};
if you are using jQuery (and it seems so ;-), take a look at the each-function in jQuery: http://api.jquery.com/jQuery.each/
that should be a lot easier for you ;-)

Javascript Dynamic GetElementByID

I would like to use the same function on two different elements without duplicating my code and changing the id. I'd like to pass the ID as a parameter into my function but it's not working.
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
Any ideas?
Looks to me as if the error is somewhere else, specificially in this line:
selected[count] = selObj.options.value;
Shouldn't that be:
selected[count] = selObj.options[x].value;
or (without the need for an extra "count" variable)
selected.push( selObj.options[x].value );
(Furthermore, you're missing a var in front of x = 0, thus making x a global variable.)

Please assist me with this simple script

I am new to JavaScript and would like to ask for some help with my simple script.
What I am trying to do is to retrieve and display the values of all list item elements in the unordered list with the help of the (for) loop. I was able to get the script display all list items in the alert window one by one. But the problem is that I need values of all list elements displayed in a table row way. Like this:
Monday
Tuesday
Wednesday
.......
Here is what I have in my script:
<script language="JavaScript">
<!--
function process() {
a = document.getElementsByTagName('li')
for (i = 0; i < a.length; i++) {
alert(a[i].childNodes[0].nodeValue);
}
}
//-->
</script>
And here is HTML code:
<body>
<ul>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
</ul>
<input type="button" value="Submit" onclick="process()" />
</body>
If that's possible at all would anyone please also explain where I am wrong in my script? Why all 3 list item values can't be shown in the alert window at once?
Thanks a lot!
First, create a string variable: var all_at_once = "". Then, add the contents of the nodeValue. Finally, alert this variable:
function process(){
var a = document.getElementsByTagName('li')
var all_at_once = "";
for(i=0;i<a.length;i++){
all_at_once += a[i].childNodes[0].nodeValue + " ";
}
alert(all_at_once);
}
The alert shows repeatedly because that is what a for loop does... it loops! The loop will iterate over the array of elements returned by getElementsByTagName, executing the loop body once for each element in that array.
If you wanted to display one alert, an option would be to build up a string containing the appropriate text, and alert it afterwards:
var yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
Some other notes on your code... you should almost always declare variables with the var keyword to prevent them leaking into the global scope. You should also always end lines with semi-colons:
function process(){
var a = document.getElementsByTagName('li'),
yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
}
<script language="JavaScript">
<!--
function process(){
var data = '';
a=document.getElementsByTagName('li')
for(i=0;i<a.length;i++){
data = data + '\n' +(a[i].childNodes[0].nodeValue);
}
alert(data);
}
//-->
</script>
You need to call alert only once if you need 1 popup with all the text.
function process()
{
var a = getElementsByTagName('li'),
text = '';
for( i = 0; i < a.length; i++ )
{
text += a[i].childNodes[0].nodeValue + '\n';
}
alert( text );
}
You can process the days in whatever manner you like by storing them in an array first, and then iterating:
var days = new Array();
var a = document.getElementsByTagName('li')
for(var i = 0; i < a.length; i++) {
days.push(a[i].childNodes[0].nodeValue);
}
for (i=0; i < days.length; i++) {
// process the day
}
See: http://jsfiddle.net/jkeyes/Cfg4k/ for a working example.
These few adjustments to your function should produce the result you want. Good luck!
What changed: 1) Set up an empty string var 2) Instead of alerting each value, just append them to the string var you created earlier 3) Finally, alert the newly created (concatenated) string!
function process() {
a = document.getElementsByTagName('li');
var days = new String("");
for (i = 0; i < a.length; i++) {
days = days+(a[i].childNodes[0].nodeValue)+"\n";
}
alert(days);
}
Now I see there have been tons of answers since opening this thread... but maybe all the different solutions will help you in different ways.

Categories

Resources