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);
Related
Can someone explain to me the parts of the for loops?
for (let i = 0; i < height; i++) {
grid += '<tr class="row-' + i + '">';
// loop for each cell
for (let j = 0; j < width; j++) {
grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"></td>';
}
grid += '</tr>';
}
Unfortunately, I don't get the grid parts. How can I write it in a different way?
The grid variable is practically the content of the table. On each grid line, a new HTML element is generated (except the last one).
For i iterations, a new row is added with a class name equivalent to the iteration index. Considering how rows are indexed vertically on a table, height is used as a metric for the y axis.
Similarly, j iterations add a new cell into the current 'i' row. Considering how a cell is combination of a row and column on a table, width is used as a metric for the x axis.
After the second (j) loop is finished, the closing tag </tr>is added in order to close the current iterated row.
In your code, the grid is simply making height number of rows and width number of rows. The grid will store this HTML code and then it must probably be replacing it somewhere using Html DOM manipulation.
What are the javascript parts in this for loop?
The loop is part of javascript, the height, width, grid variables are part of javascript. Even the HTML code you are storing is part of javascript since it is being stored in grid which is just another JS variable.
You can refer the below code to see what the code is really doing -
<!DOCTYPE html>
<html>
<body>
<p>This example demonstrates the <b>making a table using JS</b> method.</p>
<p id="demo"></p>
<script>
//var is used to store the HTML code, height and width store the number of rows and columns of table
var grid = "<table>",
height = 5,
width = 5;
for (let i = 0; i < height; i++) {
grid += '<tr class="row-' + i + '">';
// loop for each cell
for (let j = 0; j < width; j++) {
grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"> (' + i + ' , ' + j + ' ) </td>';
}
grid += '</tr>';
}
grid += "</table>";
// Below we are just replacing the HTML in p with HTML that we filled in grid
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = grid;
</script>
</body>
</html>
The grid part is just a variable name the programmer chose. It is a simple nestes for loop that will produce html that will look like this (for a 1x1 input)
With the variables i and j representing the index of their loop.
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.
So, I'm building a web site that you can play othello on as a code sample. I've got a multidimensional array as the behind-the-scenes gameboard, and then iterate through every 'td' in a table to match the value of the corresponding array member. The problem i'm encountering is that iterating through the table. and using the iterators as essentially coordinates to my array doesn't work. As the iterator increases in value, so too does the coordinates in each of my 'td's. I'm stumped, and running on fumes. Any help would be appreciated.
function gridArray() {
// creates game board's array.
for (var i = 0; i < gameArray.length; i++) {
gameArray[i] = new Array(8);
}
for (var row = 0; row < gameArray.length; row++) {
for (var col = 0; col < gameArray[row].length; col++) {
gameArray[row][col] = "green";
}
}
}
function drawGrid(){
// writes table to HTML document
var htmlString = "<table id='othelloGrid'><tr>";
for (var i = 0; i < 8; i++) {
htmlString += "<th>" + i + "</th>";
}
htmlString += "</tr>";
for (var j = 0; j < 8; j++) {
htmlString += "<tr>";
xPos = j;
for (var x = 0; x < 8; x++) {
yPos = x;
// HERE!!! I now realize javascript passes by reference, so as this loop iterates,
// every single 'td' is getting 'onclick = 'changeClass(7, 7)''.
// for my game grid to work, I need each td to have a unique xPos, yPos to
// connect back to gameArray.
htmlString += "<td onclick = 'changeClass(xPos, yPos)'></td>";
}
htmlString += "</tr>";
}
htmlString += "</table>";
return htmlString;
}
Variables are not expanded inside strings. So all your TDs have the literal attribute onclick='changeClass(xPos, yPos)' in them, not the values of these variables from the loop. So when you actually click on them, they all use the most recent values of those variables.
You need to use string concatenation to get the values. And there's no need for the global variables xPos and yPos, you can use the local j and x variables.
htmlString += "<td onclick = 'changeClass(" + j + ", " + x + ")'></td>";
I have converted an xml file into a HTML table. The function I have used is here:
document.write("<table><tr><td>ALPHA</td><td>BRAVO</td><td>CHARLIE</td><td>DELTA</td><td>
ECHO</td><td>FOXTROT</td><td>GOLF</td><td>HOTEL</td></tr>");
var x = xmlDoc.getElementsByTagName("List");
for (i = 0; i < x.length; i++)
{
document.write("<tr><td>");
document.write(i) //populates the ALPHA column
document.write("</td><td>");
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td>")
document.write(x[i].getElementsByTagName("CHARLIEITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DELTAITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td></td><td>");
document.write(x[i].getElementsByTagName("FOXTROTITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td></td><td></td></tr>");
}
document.write("</table>")
The table presents exactly what I want and I plan to add the ECHOITEMS, GOLFITEMS and HOTELITEMS later.
My issue is, in order to progress any further, I need to assign IDs to each td above, so I can pull data from the table. I am able to assign an ID to a normal HTML td but I am struggling to so within the JavaScript code above. I need to add an ID to each td consisting of a short string followed by the i number. For example, using the first few lines of code above:
var x = xmlDoc.getElementsByTagName("List");
for (i = 0; i < x.length; i++)
{
document.write("<tr id='tdalpha'+ i><td>");
document.write(i)
document.write("</td><td id='tdbravo' + i>");
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
etc. Obviously the syntax isn't correct as when I try:
var test = document.getElementById('tdalpha24')
document.write(test)
I get an error message.
Any suggestions as to how to do this properly?!
you can do so like this -
for (i = 0; i < x.length; i++)
{
document.write('<tr id="tdalpha'+i'"><td>');
document.write(i)
document.write('</td><td id="tdbravo'+i+'">');
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
.....
As almost everybody before me noticed: "do not use document.write". In most cases it's considered bad technique.
And if you still want to use it, make one big string and use document.write only one time. It will increase perfomance. Just like this:
var str = '<table><tr><td>ALPHA</td><td>BRAVO</td><td>CHARLIE</td><td>DELTA</td><td>ECHO</td><td>FOXTROT</td><td>GOLF</td><td>HOTEL</td></tr>';
for (var i = 0; i < x.length; i++) {
str += '<tr id="tdalpha'+i'"><td>';
str += i;
str += '</td><td id="tdbravo'+i+'">';
str += x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
str += '</td><td>';
str += x[i].getElementsByTagName("CHARLIEITEMS") [0].childNodes[0].nodeValue;
str += '</td><td>';
str += x[i].getElementsByTagName("DELTAITEMS")[0].childNodes[0].nodeValue;
str += '</td><td></td><td>';
str += x[i].getElementsByTagName("FOXTROTITEMS")[0].childNodes[0].nodeValue;
str += "</td><td></td><td></td></tr>";
}
str += '</table>';
document.write(str);
PS and your 'i' variable looks global to me.
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;
}