Assigning an ID to a td within a JavaScript function - javascript

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.

Related

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.

Trying to pass by value in Javascript multi-dim array

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>";

Why are these two pieces of code returning different values?

I'm learning Javascript through the online book "Eloquent JavaScript" - Which is an awesome resource by the way. I came across this function in the Data Structures chapter:
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
return table;
}
As you can see it iterates across an array, and outputs another array depending on how many times the first object had the argument:event. I rewrote this slightly different like this...
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)){
index += 1;
}
if (entry.squirrel){
index += 2;
table[index] += 1;
}
}
return table;
}
The only change is the brackets around the if statements, which I thought was best practice. However, it outputs a different value from the first piece of code. Why is this happening? Is there some scope problem that I don't understand?? If you don't know what I'm talking about, here is a link to the chapter in the book: Eloquent JavaScript
and a link to the object JOURNAL:JavaScript Object
Thanks for any help!
In the original code, this:
if (entry.squirrel) index += 2;
table[index] += 1;
is actually two unrelated statements:
if (entry.squirrel) { index += 2; }
table[index] += 1;
It's just badly indented. In Javascript, as in most C-derived languages, a single statement after an if can constitute the block to be executed when the condition is true. To include more than one statement, braces must be used.
An if statement without brackets will only execute the next instruction when the conditions are met.
The first snippet you provided contains confusing indentation as it suggests the following instruction ("table[index] += 1;") is part of the conditional statement, but in JavaScript indentation is insignificant.
So in reality, if you're using not using brackets, the first semicolon expression is where closing bracket would be.
Correctly indented code:
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
return table;
}
With brackets
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)) {
index += 1
};
if (entry.squirrel) {
index += 2
};
table[index] += 1;
}
return table;
}
You've put 'table[index] += 1;' inside an if statement, where it wasn't before. The tabbing in the original code gives a misleading impression but the original unbracketed if statement only 'wrapped' around 'index += 2;'
It's because you placed the brackets in the wrong place. It should read like so:
function tableFor(event,journal){
var table = [0,0,0,0];
for (var i = 0; i < journal.length; i++){
var entry = journal[i], index = 0;
if (hasEvent(event,entry)){
index += 1;
}
if (entry.squirrel){
index += 2;
}
table[index] += 1;
}
return table;
The table[index] line doesn't belong in the if statement.

Javascript - split string and output results on separate lines

What I'm trying to do is take a comma separated string like "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress" - split that string into and array and write a loop that outputs each array item on a separate line.
This works:
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(',');
for (var i = 0; i < output.length; i++) {
document.write(output[i] + "<br />");
}
}
but obviously it outputs to a blank page. I need it to output the results into a div.
So I try the following code but it doesn't work. It only prints out the last one "Wordpress".
function splitstr() {
var splitStr = "HTML5,CSS3,Compass,JavaScript,jQuery,PHP,Foundation,Drupal,WordPress";
var output = splitStr.split(",");
for (var i = 0; i < output.length; i++) {
document.getElementById("splitres").innerHTML = output[i] + "<br />";
}
}
what am i doing wrong?
agon
document.getElementById("splitres").innerHTML += output[i] + "<br />";
Note +. With that, you are appending HTML; without it, you are overwriting it.

Multi-line output in javascript

So let me just start out by saying that I don't have much experience with Javascript. If someone could give me a basic explanation, that would be great.
Anyways, I want to take a two dimensional matrix and print it on the screen. This is my code so far:
function matrixToString(arr) {
returnString = "";
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
returnString += Math.round(arr[i][j]*10000)/10000 + ' ';
}
returnString += "\n";
}
return returnString
}
So when I call alert(matrixToString(n)), it works as expected. However, when I use document.write(matrixToString(n)), it basically puts everything on one line and prints that line. The same applies if I put the string into a div and append the div.
I guess my question is basically how do I put multi-line outputs to HTML in javascript.
Is your multiline requirement only for presentation purpose? If so, then you just need to add '' to the end of each line. '\n' does not work when rendering HTML. Instead just replace:
returnString += "\n";
with
returnString += "<br/>";
in you code just replce \n with "br"
like this
function matrixToString(arr) {
returnString = "";
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
returnString += Math.round(arr[i][j]*10000)/10000 + ' ';
}
returnString += "<br>";
}
return returnString
}
this works for my case
document.write is outdated and hence try directly manipulate DOM.
For example:
<div id="demo"></div>
JS:
document.getElementById('demo').innerHTML = matrixToString(n);
Also with reference to this answer,
It depends on what you're doing with the text, but my guess is you're
rendering it as Html. In that case, you should be using a <br /> tag
instead of a \n.
so use returnString += "<br />"; to solve your problem.

Categories

Resources