Using a for loop within innerHTML - javascript

I want to add a box with individual boxes inside it with every age when the function is run. I tried doing it by splitting the innerHTML and using the for loop on just the agebox section so it will loop and create a new age box each time and not create a whole outerbox as well everytime like if you try loop the entire thing. I thought this would work but now it creates an age box for each loop but its placed outside the outer box and i cant figure out how to get it to loop within the outer box. If i remove the loop and just create one innerHTML then the age boxes i made manually are inside the outer box so im assuming theres a problem with the actual splitting up of the innerHTML. Thanks in advance!!
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
el1.innerHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
el1.innerHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
el1.innerHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
}

You need to store the output content as a string and then append it to the DOM. Otherwise, the div will be auto-closed.
el1 = document.getElementById('farespage');
output = "<div id=\"outerbox\">"; //initialize output string
//build output string
for(var i=13; i<=18; i++){
output +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
output += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML = output; //output to DOM
View Fiddle

The line
el1.innerHTML += "<div id=\"outerbox\">";
is actually producing
<div id="outerbox"></div>
because most browsers will auto-close the HTML tags.
You should write all your HTML into a string buffer then append it with one big call; for example:
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
// Magic begins here
var yourHTML = "";
yourHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
yourHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
yourHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML += yourHTML;
}
This has the added benefit of only touching the DOM once and not 7 times (which is generally a good thing).

Related

Why can't I add to innerHTML? [duplicate]

document.getElementById("outputDiv").innerHTML = "";
document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
document.getElementById("outputDiv").innerHTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
document.getElementById("outputDiv").innerHTML += "</tr></table>";
I want to draw a table using Javascript.
So I wrote the code like above.
I think it draw one row that has 10 columns, but it doesn't work.
Anyone know about this problem???
I ran into this problem years ago, too.
The problem is that when you use the innerHTML property to add HTML, after each update, the underlying engine will close unclosed tag (and fix other bad HTML) for you. So after the second line, the <table> and <tr> tags are automatically closed and all content after that will just be written outside the table.
Method 1
(The easy way)
Use a string to store the HTML for the whole table and update it all at once.
var HTML = "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
HTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
HTML += "</tr></table>";
document.getElementById("outputDiv").innerHTML = HTML;
​
Fiddle
Method 2
(The better way)
Use DOM functions
var table = document.createElement('table');
table.setAttribute('border','1');
table.setAttribute('width','100%')
var row = table.insertRow(0);
for(j=1; j<=10; j++){
var text = document.createTextNode(String.fromCharCode(j+64));
var cell = row.insertCell(j-1);
cell.setAttribute('align','center')
cell.appendChild(text);
}
document.getElementById("outputDiv").appendChild(table);
Fiddle
Method 2 enhanced
(The yet better way)
Use CSS instead of HTML attributes. The latter is generally depreciated as of latest specs.
A great resource to start learning CSS is the Mozilla Developer Network
Fiddle
Method 3
(The long way, but the best in the long-run)
Use jQuery.
$('<table>').append('<tr>').appendTo('#outputDiv');
for(j=1; j<=10; j++)
$('<td>').text(String.fromCharCode(j+64)).appendTo('tr');
Fiddle
I think the main problem is that your attributes are not quoted.
But it's almost always a bad idea to repeatedly update the content of a dom element in a loop—each time you update dom content it causes some internal work to be done by the browser to make sure the page layout is current.
I would build the html string up locally, then make one final update when done. (and of course make sure your attributes are quoted)
document.getElementById("outputDiv").innerHTML = "";
var newTable = "<table border='1' width='100%'><tr>";
for(j = 1; j <= 10; j++) { //opening braces should always be on the same line in JS
newTable += "<td align='center'>" + String.fromCharCode(j+64) + "</td>";
}
newTable += "</tr></table>";
document.getElementById("outputDiv").innerHTML = newTable;

Why does the array repeat the entered data from first to last

I'm having trouble with my code. I build this code but there is an issue that I cannot resolve myself. The code should work like this: When entering multiple data (name & email) the datas repeat from top to last.
For example I enter 3 names & emails one by one. I want an output of
Fred fred#gmail.com
George george#gmail.com
Laila laila#gmail.com
But instead I get this results in my table:
Fred fred#gmail.com
Fred fred#gmail.com
George George#gmail.com
Fred fred#gmail.com
George George#gmail.com
Laila laila#gmail.com
In the clearAndSave method in the end when you call $("#output").append(html); you should call $("#output").empty(); first to clear the previous results.
Change the method like this:
function clearAndSave() {
//...
$("#output").empty();
$("#output").append(html);
}
If you want to presist your initial data, modify the clearAndSave method like this:
function clearAndSave() {
// Clear fields
nameInput.value = "";
emailInput.value = "";
var html = [];
console.log(arraypeaople);
for(i = 0; x <= arraypeaople.length - 1; i++){
// Mark added rows to be able to remove them later
html += "<tr class='added-row'>";
html += "<td>" + arraypeaople[i].name + "</td>";
html += "<td>" + arraypeaople[i].email + "</td>";
html += "</tr>";
}
// Remove just the added rows
$("#output").find(".added-row").remove();
$("#output").append(html);
}

JQuery removing buttons dynamically

I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});
You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}

Adding color to particular cell in table by its id

function grid(rows, cols) {
var table = "<table id = \"myTable\">";
var size = (1 / rows * 525) + "px";
for (i=0; i<rows; i++) {
table += "<tr>";
for (j=0; j<cols; j++) {
var ID = i+','+j;
table += "<td id = \"ID\" >"+"</td>";
}
table += "</tr>";
}
table += "</table>";
var ID2 = randomFunction(rows, cols);
alert(ID2);
document.ID2.style.color = "red";
//document.getElementById(ID2).style.color = "#ff0000";
//table1.rows[1].cells[0].style.backgroundColor = "#003F87";
//id.style.backgroundColor='#003F87';
$("#container").empty().append(table);
}
I have generated table dynamically in javaScript specifying number of rows and columns. I have given id to each cell. I need to change the color of particular cell whose id is generated by random function. I tried in different ways but no solution.
One by one:
document.getElementById(ID2).style.color = "#ff0000";
won't work, because at this moment, the table is not in the dom, so document.getElementById(ID2) will return nothing.
table1.rows[1].cells[0].style.backgroundColor = "#003F87";
won't work, because table is a regular string, and strings don't have a rows property.
id.style.backgroundColor='#003F87';
won't work because id is again, a simple string. What would work is, to add the table to the dom first, using $("#container").empty().append(table);, and then do the setting of the color, using straightforward
document.getElementById(ID2).style.backgroundColor = "#ff0000";
or with jquery:
$("#"+ID2).css({backgroundColor: "#ff0000"}).
I would also recommend inserting a space ( ) in the table cells (note that your current code is incorrect, it sets the id for all the cells to the string "ID"), using
table += '<td id = "'+ID+'"> </td>';
otherwise the table could be rendered a little odd. Also id in the format 1,2 might cause problems, how about
var ID = 'td_'+i+'_'+j;
which gives you an ID like td_1_2, which won't mess up any browser.

HTML is coming out as plaintext

I am trying to add some text to an element, however it is all coming out as plaintext, even when there is an HTML element included.
for (i = 0; i < restext.length; i++) {
var p = document.createElement("p");
p.innerHTML = "<p>" + restext[i].innerHTML + "</p>";
document.getElementById("registererrors").appendChild(p);
}
However with this, it prints out the tag:
The name <em class="placeholder">name</em is already taken.
How do I make it so that it processes this tag too?
Change
p.innerHTML = "<p>" + restext[i].innerHTML + "</p>";
to
p.innerHTML = restext[i].innerHTML;
The problem is that after you create p element with document.createElement you add <p></p> inside of it. And inside of the inner p tag you insert other HTML code, which automatically gets escaped.

Categories