Using for loops - javascript

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.

Related

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

Javascript For loop appending child only appends first element, then throws error

I'm looping through a js object with a nested for loop, stated below, it appends the first element correctly, but then throws the following error:
Can't set the property className of an undefined reference or empty reference. (not sure if exact error, translating from Dutch...)
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true}); //returns: [{"VideoName":"timelapse aethon2","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"},{"VideoName":"timelapse aethon3","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"}]
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
//alert(resultSet);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
videoElement.appendChild(document.createElement('div'));
videoElement.children[i].id='allVid' + i;
videoElement.children[i].className='col-md-4 col-xs-12';
//alert(typeof key)
var card = document.getElementById('allVid' + i);
alert(i);
card.appendChild(document.createElement('div'));
card.children[i].className='card card-block';
card.children[i].innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
}
}
}
}
[EDIT] added screenshot of how it looks
Your code has some significant logic issues. You're using nested loops, but appending to an element assuming that the outer loop counter will let you index into that element's children to get the element you just appended. Later, you try to get that same element again using getElementById. Then, you append a new element to your newly-created element, but try to access that new element using children[i] on the one you just created — at that point, the card element will only have a single child, so as of the second outer loop, it will fail.
createElement returns the element to you, so there's no reason at all to try to access it via children[i] (either time) or getElementById.
See comments:
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true});
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// Create the card, give it its id and class
var card = document.createElement('div');
card.id='allVid' + i;
card.className='col-md-4 col-xs-12';
// Create the div to put in the card, give it its class and content
var div = document.createElement('div');
card.appendChild(div);
div.className='card card-block';
div.innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
// Append the card
videoElement.appendChild(card);
}
}
}
}
Side note: arrLenght looks like a typo (it should be th, not ht), but moreover, there's no reason to use a function to get the length of an array; it's available via the array's length property: parsedLength = parsed.length.
Side note 2: You may find these ways of looping through arrays useful.
Your problem is the if within the nested for:
if(obj.hasOwnProperty(key)) { ...
The variable i is increased even if the property is not "owned" (when the if condition returns false), so next time that the condition is true, i is out of bounds.

Is there a way to loop this?

Is there a way to loop a declaration of a variable? just a loop to help me declare the variables so i dont have to do the monotonous work of change the numbers of the variable
var height1 = document.getElementById('height1').value;
var height2 = document.getElementById('height2').value;
var height3 = document.getElementById('height3').value;
var height4 = document.getElementById('height4').value;
var height5 = document.getElementById('height5').value;
var height6 = document.getElementById('height6').value;
var height7 = document.getElementById('height7').value;
var height8 = document.getElementById('height8').value;
var height9 = document.getElementById('height9').value;
var height10 = document.getElementById('height10').value;
var height11 = document.getElementById('height11').value;
var height12 = document.getElementById('height12').value;
var height13 = document.getElementById('height13').value;
var height14 = document.getElementById('height14').value;
var height15 = document.getElementById('height15').value;
var height16 = document.getElementById('height16').value;
This is not a right way of coding that, Just do like,
var heights = [];
Array.from(document.querySelectorAll("input[id^=height]")).forEach(function(itm){
heights.push(itm.value);
});
And now you can iterate the array heights to manipulate the values as per your requirement.
The logic behind the code is, querySelectorAll("input[id^=height]") will select the input elements that has id starts with the text height. Since the return value of querySelectorAll is a nodelist, we have to convert it as an array before using array functions over it. So we are using Array.from(nodelist). That will yield an array for us. After that we are iterating over the returned array by using forEach and pushing all element's value into the array heights.
This is almost always an indication that you want an array. Something like this:
var heights = [];
for (var i = 1; i <= 16; i++) {
heights.push(document.getElementById('height' + i).value);
}
Then you can reference a value from the array with something like:
heights[1]
Though technically since in JavaScript your window-level variables are indexable properties of the window object, you can essentially do the same thing with variable names themselves:
for (var i = 1; i <= 16; i++) {
window['height' + i] = document.getElementById('height' + i).value;
}
Then you can still use your original variables:
height1
Though in the interest of keeping things outside of window/global scope, maintaining the array seems a bit cleaner (and semantically more sensible).
This seems to be a good use case for an object:
var heights = {};
for (var i = 1; i <= 16; i++) {
heights[i] = document.getElementById('height' + i).value;
}
Maybe its time to introduce function:
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
function getHeight(id) {
return document.getElementById(id).value;
}
Call with the wanted id and use it like a variable.
getHeight('height1')
Normally you would put them in an array.
var heights = []
for (i = 1; i < 17; i++) {
heights[i] = document.getElementById('height' + i).value;;
}
Beware this will give you a hole at the start of the array ie heights[0] has nothing in it. If you use this to iterate it won't matter...
for (var i in heights) {
alert(heights[i]);
}

My java script array doesn't have a length

I have the following code:
//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
var addData = {
id : x[i].id,
value : x[i].value
};
inputData[i] = addData;
$('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}
I'm attempting to pass the form data from a previously made form to another javascript function. Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. I determined this is because inputData.length is undefined. I was under the impression that declaring it as inputData = {}; made it an array and thus had a default length value. How can I change this to have the correct length?
Edit
Several commenters have said that var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. Adding the line in the code above, has produced this output.
My x.length property 18
serialNumber : 456
someDatafield : someInput
You've declared it as an object.
Perhaps var inputData = []; will give you better results.
{} is an object, not an array.
You want [].
Also, getElementById() does not return an array; your entire code makes no sense.

Javascript for loop function array

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>

Categories

Resources