Multi-line output in javascript - 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.

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.

Assigning an ID to a td within a JavaScript function

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.

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.

FOR IF Loop in javascript

I have a simple question. I want to make an if statement in this code (if(i=2){str += 'test';}):
var data = response.DATA;
var str = '<ul>';
for (var I = 0; I < data.length; I++) {
str += '<li>' + data[I][1] + '</li>';
if(I=2){str += 'test';}
}
str += '</ul>';
$('#output').html(str);
}
When I do, it's placing the word 'test' not only at row 2, but on every row.
Use == or === to compare two values :
if (I===2) {str += 'test';}
The result of I=2, which changes the value of I, is 2, which evaluates as true in an if.
You have a typo in your script:
if (I=2) ...
means that I is always 2 because you're assigning 2 to it.

Looping and finding empty array

I'm working on project in which I have to create a search engine through jQuery. Everything has been going great until I started looping through the array.
I don't know whether I'm doing it wrong, but for some reason, when I use a conditional it does not output the statement I want it to say. If I change the conditional to say whether there's something in the array output this, it does. But if the array is empty it does absolutely nothing. Why is that?
for(var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if(response.length === 0){
$('' + '<ul>' +
'<li><span>Nothing found, try again</span></li>' +
'</ul>'
).appendTo(searchResults);
}
$('' + '<ul>' +
'<li><img src="" /><span> '+searchItemRes.title+'</span></li>' +
'</ul>'
).appendTo(searchResults);
}
Consider this:
// declare local variables
var str, i, item;
// build the HTML source code string
if ( response.length === 0 ) {
str = '<ul><li><span>Nothing found. Please, try again.</span></li></ul>';
} else {
str = '<ul>';
for ( i = 0; i < response.length; i += 1 ) {
item = response[i];
str += '<li><img src=""><span> ' + item.title + '</span></li>';
}
str += '</ul>';
}
// append the string to the DOM
$( searchResults ).append( str );
First off, declare the local variables at the top of the function. As you can see, my code uses 3 local variables.
Next, I doubt that you want to create one UL (list-holder) for each result. It makes more sense to have one UL element which contains all the results (which is what I've implemented in the above code).
Also, I recommend manipulating the DOM only once at the end - the live-DOM should be touched as few times as possible. Therefore, the above code builds the HTML source code string "off-DOM", and only in the end appends (the whole thing) to the DOM.
for (var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if (response.length === 0) {
$('<ul><li><span>Nothing found, try again</span></li></ul>').appendTo(searchResults);
}
...
}
That condition will never be executed. If i = 0 and j = response.length and it's iterating i < j then it won't iterate at all if response.length == 0 because 0 < 0 will just break out of the loop.
How can code that triggers on response.length == 0 ever execute inside a loop that iterates response.length times?
Perhaps you meant:
if (response.length === 0) {
$('<ul><li><span>Nothing found; try again</span></li></ul>').appendTo(searchResults);
}
else {
for (var i = 0, j = response.length; i < j; i++) {
var searchItemRes = response[i];
$('<ul>' +
'<li><img src="" /><span>' + searchItemRes.title + '</span></li>' +
'</ul>'
).appendTo(searchResults);
}
}

Categories

Resources