Javascript loop not appending value in each container - javascript

This might be such a simple fix, but I think I've been stuck on this issue for way to long. Can someone spare a pair of eyes and see where I'm messing up?
I'm pulling data from a json file and trying to append the right value with the right container. Right now it's placing all the values in the first div container.
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
var metaDataContainer = "<div id='itemMetaDataContainer_"+xx+"'>Meta Data:" + metaDataArray[xx].name + "-</div>"
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
$('#itemMetaDataContainer_'+xx).append(metaDataArray[xx].meta_values[xxx]);
}
itemDetailsDiv.append(metaDataContainer);
}

you are trying to select a container before you append it to the details div. try appending the data values array to your container the following way:
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
var metaDataContainer = $("<div id='itemMetaDataContainer_" + xx + "'>Meta Data:" + metaDataArray[xx].name + "-</div>");
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
metaDataContainer.append(metaDataArray[xx].meta_values[xxx]);
}
itemDetailsDiv.append(metaDataContainer);
}
UPDATE:
a jQuery object holds the plain html element in index [0] (assuming its not an array).
to get the html out of metaDataContainer you can find it in metaDataContainer[0]
therefore, in order to append the jQuery object metaDataContainer to the plain html element itemDetailsDiv, you need to do the following:
itemDetailsDiv.innerHtml + = metaDataContainer[0];
UPDATE 2:
Here is a plain JavaScript solution:
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
//initializing the html string with the container opening tag and the description:
var metaDataContainer = "<div id='itemMetaDataContainer_" + xx + "'>Meta Data:" + metaDataArray[xx].name;
//looping through the values and adding them to the html string:
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
//create a span for each value and add it to the html string
metaDataContainer+="<span>" + metaDataArray[xx].meta_values[xxx] + "</span>";
//add a line break just for aesthetics, you can change to suit your formatting requirements
metaDataContainer+="<br/>";
}
//finish by adding a closing tag for the container
metaDataContainer+="-</div>"
//append the new html string to the details div
itemDetailsDiv.innerHtml +=metaDataContainer;
}

Related

Can't pass variable to .getRange()

I'm trying to write a script that gets a range who's size is based on a constant. My the code I've been trying is below
//Save range based on number of components
var numComponents = 3;
var compRange = SpreadsheetApp.getActiveSheet().getRange(15,3,numComponents,3);
var compValues = compRange.getValues();
var components = "";
//Convert the components into paragraph form
for (var row = 0; row <= numComponents ;row++){
components = components + compValues[row][1] + " " + compValues[row][2] + " "+ compValues[row][0]+ "\n";
};
Whenever I run this code, I get an error saying
Error: Cannot read property 1 of undefined
When I replace numComponents with 3, the code works perfectly, however that will not always be the case. How can I make it work properly?
It's very likely that the problem is this expression row <= numComponents
Replace
for (var row = 0; row <= numComponents ;row++){
by
for (var row = 0; row < numComponents ;row++){

How to print a javascript array values in a jQuery .html() function?

I have a JavaScript array that contains a set of strings. I want to display them in a HTML div element by line by line using j Query or JavaScript.
My code is up to now:
var data = data;
for (i = 1; i <= data.length; i++) {
data[i] = data[i] + '<br />';
$(target).html('<a>'+data[i]+'</a>');
}
My data is displayed in this moment right now.
Labelling MachinesLabels - Plastic, Metal, Foil etcLabels FabricLaboratories - MedicalLaboratories - TestingLaboratory Equipment & SuppliesLaboratory Equipment Services & Calibration
I want them displayed like this as links (inside tags):
Labelling Machines
Labels - Plastic, Metal, Foil etc
Labels Fabric
Laboratories - MedicalLaboratories - Testing
Laboratory Equipment & Supplies
Laboratory Equipment Services & Calibration
Thanks in advance
You should add the breaks outside of the link tags and use .html() only once, as it completely replaces the innerHTML of the given element, i.e.
str = "";
for (i = 1; i <= data.length; i++) {
str += "<a>" + data[i] + "</a><br />";
}
$(target).html(str);
I would suggest another approach, to use innerHTML (javascript) or append (jquery) as another answer has already mentioned
for (i = 1; i <= data.length; i++) {
target.innerHTML += "<a>" + data[i] + "</a><br />";
}
Your code is incomplete here.Not sure if you have declare variable i anywhere in code.Also you are starting to loop from 1st index
Instead of appending to DOM on every iteration,create a string and concat the value to it. Append it on completion of the iteration.
var data = data,
htmlString="";
for (var i = 0; i <= data.length; i++) {
htmlString+= data[i] + '<br />';
}
$(target).append(htmlString);
The cleanest way will be wrapped in a div. And you need to use .append() method to not override the initial data that is already added to the target.
var data = ["Hello", "World", "Lorem", "Ipsum", "More length"];
for (var i = 0; i < data.length; i++) {
$("#result").append('<div>' + data[i] + '</div>');
}
.link {
color: #5ca5cc;
margin-bottom: 10px;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Clean and more simple code along with working demo.
Instead of a for/loop you could use ES6 in one line with map and a template literal.
$(target).html(arr.map(el => `<a>${el}</a><br/>`));
DEMO
var data = data;
var str = '';
for (var i = 1; i <= data.length; i++) {
str += `<a>${data[i]}<br /></a>`;
}
$(target).html(str);
Try this.

Js unterminated string constant for .append dynamic table

I am creating a table dynamically using data in an array:
var toAppend = $("#tablediv");
toAppend.append("<table id=\"grid\"><tr><th>(labels)</th>");
for (var f = 0; f < seriescount; f++)
{
toAppend.append("<th>" + series[f] + "</th>");
}
toAppend.append("</tr></table>");
The final line returns an 'unterminated string constant' error. This goes away by removing the line or changing its contents - this is something to do with it being a closing tag.
This code is in tags within C# Razor.
A document fragment is always closed. You can't append half elements.
So when you do
toAppend.append("<table id=\"grid\"><tr><th>(labels)</th>");
what you really do is
toAppend.append("<table id=\"grid\"><tr><th>(labels)</th></tr></table>");
A simple solution here is to build an HTML string and do only one append with the complete string :
var h = "<table id=grid><tr><th>(labels)</th>";
for (var f = 0; f < seriescount; f++) {
h += "<th>" + series[f] + "</th>";
}
h += "</tr></table>";
$("#tablediv").append(h);

how to split & add array values into different 'div' components without using "if" condition?

I am using HTML5 + javascript for developing a webpage. I have an array with 100 values. And i have a 10 different HTML5 "div" components. I'm adding 1st 10 array values into 1st "div", 2nd 10 array values into 2nd "div" and similarly goes on. I am using HTML DOM to add these array values into particular "div" component.
Here i have used "if...elseif" condition & is working fine.
But i'm asked not to use "if" condition to add array values into different 'div' elements. Is there any other possible methods to do this?
My div components are 'div1','div2'.......'div10'(added in body tag)
var myArray = ['user1', 'user2', 'user3', ..., 'user100'];
for(i=0;i<myArray.length;i++)
{
var a = document.createTextNode(myArray[i]);
if(i<=10)
{
var container1 = document.getElementById('div1');
container1.appendChild(a);
}
elseif(i>10 && i<=20)
{
var container2 = document.getElementById('div2');
container2.appendChild(a);
}
...
...
...
...
else
{
var container10 = document.getElementById('div10');
container10.appendChild(a);
}
}
It's bad solution. The better one is following:
for(j=0;j<10;j++)
{
//get div1, div2, div3 etc.
var container = document.getElementById('div'+(j+1));
for(i=0;i<10;i++)
{
//get proper value
var a = document.createTextNode(myArray[i+j*10]);
//insert value into container
container.appendChild(a);
}
}
var set=myArray.length/10; /** no of sets of 10 **/
for(i=0;i<set;i++){ //loop through sets
for(int j=(i*10);j<(i+1)*10;j++){ //loop through each set 0-9, 10-19
var a = document.createTextNode(myArray[j]);
document.getElementById('div'+(i+1)).appendChild(a);
}
}
var myArray = ['user1','user2','user3',...'user100'];
for(var i = 0; i < 10; i++) {
var container = document.getElementById("div" + (i + 1));
for(var j = 0; j < 10; j++) {
container.appendChild(document.createTextNode(myArray[(i * 10) + j]));
}
}
If you don't mind array values being inserted into each div as one text node, you could do:
var div, i;
for (i = 1; i < 11; ++i) {
div = document.getElementById('div' + i);
div.innerHTML = myArray.splice(0, 10).join(' ');
}
You don't need 2 for loops. Do you?
for (var i = 1; i <= 100; i++)
{
document.getElementById('div' + ( i%10 + 1)) //this will give your target div
}
P.S: spare me... Typing on mobile...

Appending to the Dojo DIV [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Appending Javascript Array Values to the DOJO div
Hi ,
I have Array of values as shown :
var myarray2 = [];
myarray2.push("10-FEB-11");
myarray2.push("11-FEB-11");
myarray2.push("12-FEB-11");
myarray2.push("13-FEB-11");
myarray2.push("14-FEB-11");
myarray2.push("15-FEB-11");
I am trying to append it to the DIV , but Data is coming upto Alert , but not getting displayed using innerHtml property , Please help
var ol = document.getElementById('hrXAxisSlider').getElementsByTagName('ol');
var i;
var htmlFrag = '';
for (i = 0; i < 11; i++) {
htmlFrag += '<li>' + myarray2[i] + '</li>';
}
alert(htmlFrag);
ol.innerHTML = htmlFrag.value;
getElementsByTagName return a NodeList. It does NOT return a single node.
You have to do: getElementsByTagName("ol")[0] to get the first ol node.
Modify your code slightly, as follows, i am given sample code.
function start(){
var myarray2 = [];
myarray2.push("10-FEB-11");
myarray2.push("11-FEB-11");
myarray2.push("12-FEB-11");
myarray2.push("13-FEB-11");
myarray2.push("14-FEB-11");
myarray2.push("15-FEB-11");
var ol = document.getElementById('hrXAxisSlider');
var i;
var htmlFrag = '';
htmlFrag="";
for (i = 0; i ' + myarray2[i] + '';
}
htmlFrag+=""
alert(htmlFrag);
ol.innerHTML = htmlFrag;
}
in body part give one DIV and id is "hrXAxisSlider"
oneone
i am given div content is sample
if u provide u r mail id i will send complete code

Categories

Resources