Issue with Javascript loop - javascript

My div class array looks like this
[ <div class=​"divtitle" style=​"height:​ 22px;​">​A​</div>​ ,
<div class=​"divtitle" style=​"height:​ 22px;​">​W​</div>​ ,
<div class=​"divtitle" style=​"height:​ 22px;​">​E</div>​ ,
<div class=​"divtitle" style=​"height:​ 22px;​">​AA</div>​ ]
I have this javascript function
var products= document.getElementsByClassName("divtitle")[0].innerHTML;
return products;
But now i have more than 1 product name in the div and i am wondering how to write loop in JavaScript using this function.
var products= document.getElementsByClassName("divtitle").innerHTML;
var arrayLength = products.length;
for (var i = 0; i < arrayLength; i++) {
return products[i];
}
Can you please tell me what is wrong here?
Thanks

Assuming your div innerHTML looks something like this "product1, product2, product3.." when you get it products will be a string, and not a list.
When you loop over string length you actually loop over its characters.
Try to do something like this:
var products= document.getElementsByClassName("divtitle").innerHTML;
return products.split(",")
If you separate different products with comma, this should return a list of products.
PS. your question is a little unclear, it would help a lot if you show an example of the html elements, eg how divtitle looks like.

You're returning the entire product array within your for loop. you need to write something like this:
var products= document.getElementsByClassName("divtitle").innerHTML;
for (var i = 0; i < products.length; i++) {
/*you will write your code that you want to do with each product here
using the i index, such as: */
console.log(products[i])
}

Related

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

how to split the textarea into parts in javascript

I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]

Print data value of array

I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/

javascript getelement where value contains specific string

I was wanting to count the occurrences of input fields that has a class name of text where that text input contains a specific value.
document.getElementById('c_files').getElementsByClassName('text').length;
So far this counts all textboxes with the class name of text but how can i make it value specific, say if i have 50 textboxes but i only want to count the ones where the value of that textbox contains abc somewhere within the string.
Thanks.
Edit: Thank you everyone for your time and answers, i have voted you all up, but i prefer John Bupit's solution out of them all so thats the one i will accept. Thanks again.
You can iterate over the elements and see which ones have the desired value:
var elems = document.getElementById('c_files').getElementsByClassName('text');
var count = 0;
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.match(/abc/)) count++;
}
You can select all textboxes first and after that filter those matching your criteria. For example, by using Array.prototype.filter method:
var allText = document.getElementById('c_files').getElementsByClassName('text'),
filtered = [].filter.call(allText, function(textbox) {
return textbox.value.indexOf('abc') > -1;
});
Above code will produce and array of text elements where value contains substring "abc".
Hi I think you need to review this SO post-
https://stackoverflow.com/a/9558906/3748701
https://stackoverflow.com/a/10095064/3748701
This is something which would help in getting your solution.
You'll need to loop over all of the text boxes with the specified class and calculate it from there.
Something like the following logic should work:
var counter = 0;
var inputElements = document.getElementById('c_files').getElementsByClassName('text').length;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements.value == "someText") {
counter++;
}
}

Using c# code in javascript

I am trying to use C# in javascript like we are using it in MVC Razor View using # sign,
like suppose an array name list is passed to the View so we can access it in View like:
View
Length of array : <input type="text" value="#Model.list.Length" />
Or we can iterate list array also like:
#for(int i=0; i< Model.list.Length; i++)
{
console.log(Model.list[i]);
}
But my question is how we can iterate or use this array in the javascript code , something similar to :
JS
for(var i=0; i<#Model.list.Length; i++)
{
$("body").append("<h1></h1>").html(#Model.list[i]);
}
Thanks !
As i posted in my comment, this is a bit tricky. However, you can try to construct a javascript object with your c#.
Something like this (i don't know how this works exactly...):
var array = [
#for(var i = 0; i < Model.list.Length-1; i++){ #Model.list[i] , }
#Model.list[length]
]
which should result in:
var array = [
val1,
val2,
val3,
valn
]
Now you have an js var array, you can work with in your entire document.
You can't do it exactly that way. What you can do is use the C# to generate the javascript code for each line like this:
//...javascript code...
#for(var i = 0; i < Model.list.Length; i++)
{
$("body").append("<h1></h1>").html('#(Model.list[i])');
}
//...more javascript code...
This should output like this:
//...javascript code...
$("body").append("<h1></h1>").html(listitem0);
$("body").append("<h1></h1>").html(listitem1);
$("body").append("<h1></h1>").html(listitem2);
//etc.
//...more javascript code...

Categories

Resources