I'm using a very simple function to present within a table the name of a person and their age given by the user through a prompt window. The only problem I'm having is that whenever the user adds a second name and age, JS replaces the previous one. It won't add a second row.
http://jsbin.com/jamobifu
JS
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
HTML
<h1>Making A List</h1>
<p>This program will create a list based on two question which will be asked to you. Type the name of the person and their corresponding age. Output will be presented in a customized table.</p>
<input type="button" value="Create List" onclick="table()" />
<table id="tableOfPeople" style="width: 600px; margin-left: auto; margin-right: auto; margin-top: 50px; background-color: #74a9cb; color: white; border: 1px solid #127bbb"></table>
You shouldn't use innerHTML to modify the contents of a table as it will fail in versions of IE upto and including 9 at least (where innerHTML is readonly for a number of table related elements*). So you should be using DOM insertRow and insertCell methods (or createElement and appendChild, but the insert methods do two steps in one):
var row = document.getElementById("tableOfPeople").insertRow(-1);
var cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(name));
cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(age));
* MSDN::innerHTML property
The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.
You Forgot += instead =
function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");
/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}
Your problem is right here. Every time the user adds a new name you are replacing the old information instead of adding to it. Any time the innerHTML method is called on an element it will delete the old HTML information inside of the element.
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
What you could do is store this information to a variable and then add that with the new information.
Something along the lines of:
var information = document.getElementById("tableOfPeople").innerHTML;
document.getElementById("tableOfPeople").innerHTML = information + "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
This is because you are replacing the innerHTML with the new table row, not adding to it. You can solve this pretty easily by replacing
document.getElementById("tableOfPeople").innerHTML = "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
With:
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
The += operator adds to the existing value. For example, the following code:
a = 4;
a += 2;
alert(a); //alerts 6
As #cookiemonster pointed out, there are numerous caveats to this approach. The cost of using .innerHTML to alter the DOM is high and destructive. It requires the DOM to be parsed into a string, the string altered, then parsed back into the DOM. This process destroys any event listeners or other information you may have had on the elements.
It will also make things more difficult as you wish to extend the functionality of the code, to add things like the ability to delete rows.
#RobG has presented a much better solution, and as he points out .innerHTML can fail in various versions of IE.
Related
I have a form I enter student info (name, email, address) and I was able to add a new row (made of three columns) using JS after I click a button. Every time a new row is created, three new columns are created with three input boxes each with its own element ID. So far so good. However, now I can't for the life of me figure out how to remove the last row that was added. Below is my code:
var student_ids = 0;
document.getElementById("studentCount").value = student_ids;
function anotherStudent(){
document.getElementById("student_info").innerHTML +=
"<div class='section colm colm4'>"+
"<input type='text' name='stud_name_" + student_ids + "'id='stud_name_" +student_ids+ "'class='gui-input' placeholder='Student name'>"+
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='email' name='stud_email_" + student_ids + "'id='stud_email_" + student_ids + "'class='gui-input' placeholder='Email'>" +
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='text' name='stud_address_" + student_ids + "'id='stud_address_" + student_ids + "'class='gui-input' placeholder='Address'>"+
"</div><!-- end section -->" ;
student_ids = ++student_ids;
document.getElementById("studentCount").value = student_ids ;
}
function removeStudent(){
var x = document.getElementById('stud_name_'+student_ids);
var y = document.getElementById('stud_email_'+student_ids);
var z = document.getElementById('stud_address_'+student_ids);
x.remove();
y.remove();
z.remove();
}
Edit:
You are not removing the divs, only the inputs themselves. You are also incrementing the student_ids global variable after you insert a row. This means that the removeStudent() function will always try to remove a non-existing row.
It would be better to pass the desired student_ids to removeStudent(), or manually de-increment the value.
In older environments (such as Explorer):
You cannot directly remove DOM elements from JavaScript. It's a bit unintuitive, but you have to go to the parent of that element and remove it from there:
var element = document.getElementById('stud_name_'+student_ids);
element.parentNode.removeChild(element);
I have a table in HTML where the ID is dynamically generated from a row counter:
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>"
+ "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>"
+ "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>"
+ "</tr>"
I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input.
Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding:
$(#maxAltitude).prop("disabled", true);
How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed.
I've tried jQuery and javascript but can't seem to find a good way to do this:
<option onclick="shapeSelect()" value="sphere">Sphere</option>
<option onclick="shapeSelect()" value="cylinder">Cylinder</option>
function shapeSelect() {
var shapeSelects = document.getElementsByName("shapeSelect");
var maxAlts = document.getElementsByName("maxAlt");
for(var i = 0; i < shapeSelects.length; i++) {
switch(shapeSelects[i].value) {
case "sphere":
maxAlts[I].disabled = True;
break;
case "cylinder":
maxAlts[i].disabled = False;
}
}
}
With the above code I get: SyntaxError: unexpected token: identifier whenever shapeSelect() is fired.
I've modified the code as follows:
<table class="myTable" id="myTable"></table>
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option value=\"sphere\">Sphere</option>"
+ "<option value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude_" + rowCount + "\"</td>"
+ "<td><input class=\"maxAltitudeInput\" type=\"text\" id=\"maxAltitude_" + rowCount + "\" disabled></td>"
+ "</tr>"
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
And still nothing happens when I change the shape selector dropdown.
EDIT:
Apologies on the naming mismatches. My dev machine is on an airgapped network and I was hand jamming the post here on Stack Overflow. The rowCount variable was being created and incremented in another function. I was trying to only put relevant code in the post for brevity.
I was missing a class from shapeSelector. That was the missing link. It works now!
jQuery actually makes this really easy by binding this to whichever element triggered an event.
For instance, instead of writing a generic function for when that value changes, you could use jQuery to bind an event listener to them:
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
You'll notice a few things in this snippet:
The element we are binding the listener to is the table, not the individual row. That's because the row is dynamic, and we don't want to have to keep adding listeners every time we add a row. Instead we add it to the parent which is stable, but then we specify that we are interested in its children that match ".shapeSelector"
The listener relies on class names, not IDs, since we want to match multiple copies of them, not just a specific one. So you'd need to add those class names or a similar way of matching more than one item
Inside the callback function that runs, you'll notice a couple uses of this. jQuery has bound that to the element that triggered the event listener, in this case, the <select> control. So when we use this, we have to think of it from that perspective. We can get its value by $(this).val(), we can find its parentt with $(this).parent(), etc. In this case, I'm travelling up to the nearest tr, then from there down to that tr's input that I want to disable. You'd need to adjust a little depending on your dom.
Also note that this is a DOM element, not a jQuery result. That's why when we want to run more jQuery commands on it, we have to put it in $() again.
That's how I'd approach it. We don't have your entire code here, so you'll have to adjust a bit, but hopefully that pushes you off in the right direction.
EDIT
To be honest, there were a lot of naming mismatches and things that didn't line up. For instance, you were attempting to append onto a tbody tag, but that tag didn't exist. You were using a rowCount variable, but didn' ever set that up or increment it. The select tag sill didn't have the class name you were trying to use.
I suggest you look at your code piece by piece, ask yourself what you're telling the browser to do, and then do that instruction in your mind to make sure the computer can do it.
HTML:
<table class="myTable" id="myTable"><tbody></tbody></table>
JavaScript:
var rowCount = 0;
function addRow(){
$('.myTable tbody').append(`<tr name="tableRow">
<td>
<select class="shapeSelector" id="shapeSelect_${rowCount}">
<option value="sphere">Sphere</option>
<option value="cylinder">Cylinder</option>
</select>
</td>
<td><input type="text" id="altitude_${rowCount}" /></td>
<td><input class="maxAltitudeInput" type="text" id="maxAltitude_${rowCount}" disabled></td>"
</tr>`);
rowCount++;
}
$('.myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
});
addRow();
addRow();
addRow();
https://jsfiddle.net/32vnjq81/
I have html table on my parent page that has some data:
Begin Date End Date City
03/28/2017 Toronto
03/25/2017 03/26/2017 Miami
03/22/2017 03/24/2017 Chicago
03/16/2017 03/21/2017 Dallas
03/10/2017 03/15/2017 Austin
After use update the element from specific row I would like to replace entier content of that row. Each row had unique id. I have to do this with plain JavaScript Vanilla. Here is my example what I have so far:
fnObj.DATA is numeric and I get that after my ajax call is successfully completed. I use the id from that callback function to detect the row that I want to update. I'm not sure what is the best technique to replace all the td tags. This technique works with one exception. There is no id on the row that I have replaced the data. If anyone knows better way to do this please let me know. Thank you.
window.parent.document.getElementById("New_"+fnObj.DATA).outerHTML = "<td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>document.getElementById("newCity").value</td>";
window.parent.document.getElementById(dType+"_"+fnObj.DATA).id = 'New_'+fnObj.DATA;
Try this:
var newtr = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
$("#New_"+fnObj.DATA ).replaceWith(newtr);
If you don't want to use jquery you can use something like:
var currentTr = document.getElementById("New_"+fnObj.DATA), parent = currentTr.parentNode,
tempDiv = document.createElement('div');
tempDiv.innerHTML = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
var input = tempDiv.childNodes[0];
parent.replaceChild(input, currentTr);
I am dynamically creating a table through Javascript and I DO want the table to continue off the right side of the page. Doing this manually lets the table continue off, but once I feed this into a for loop the <td>s wrap into a second line in the rendered HTML, creating two or more table rows when they reach the end of the page.
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0">
<tr></tr>
</table>
</div>
This is inside a table of its own (no style formatting). Then the Javascript:
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>"
for(i=0; i<numpanels; i=i+1)
{
panelindex.innerHTML = panelindex.innerHTML + "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + zeroFill(i,2) + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>\n";
}
panelindex.innerHTML = panelindex.innerHTML + "</tr></table>"
You may notice that there is a <div> in the <td> and that is so I can apply a border marking the panel. Without the <div> it seems I cannot do that, and there are some other undesired effects. Any ideas what I can do so that all the <td>s end up on one line rather than split to a new line?
Example of what I want: http://edwardleuf.org/comics/jwb/009-conmet
What is happening: https://jsfiddle.net/w4uh0a3j/7/
Click the Show link.
innerHTML does not hold the string value you assign to it.
It parses the value as HTML, creates a DOM from it, inserts it into the document and then, when you read it back, it converts that DOM back into HTML.
This means that the string you assign is subject to error recovery and normalisation. In particular, the end tags you omitted are fixed.
panelindex.innerHTML = "<table border='0'><tr>"
console.log(panelindex.innerHTML);
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0"><tr>
</tr></table>
</div>
So when you start appending more data to it:
panelindex.innerHTML = panelindex.innerHTML + "<td>etc etc
You end up with:
<table border="0"><tbody><tr></tr></tbody></table><td>etc etc
Store your data in a regular variable. Only assign it to .innerHTML once you have the complete HTML finished.
A better approach then that would be to forget about trying to build HTML by mashing strings together (which is error prone, especially once you start dealing with characters that need escaping in HTML) and use DOM (createElement, appendChild, etc) instead.
OK,here is fixed html and js code. It seems like innerHTML fixes missing closing when updating html before all the code is building the rest of innerHTML. This code works :
<div id="panelindex" style="overflow:scroll;text-align:center;">
</div>
and js code :
var numpanels = 100;
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>";
var html = "<table border='0'><tr>";
for(i=0; i<numpanels; i=i+1) {
html += "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>";
}
html += "</tr></table>";
document.getElementById("panelindex").innerHTML = html;
I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S
the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)
function createPlayGround(rows, who)
{
$('#container').hide();
var grid = document.getElementById("Grid" + who);
var sqnum = rows * rows;
var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
innercode += '<tr>';
for (i=1;i<=sqnum;i++)
{
var rowno = Math.ceil(i / rows);
var colno = Math.ceil(i - ((rowno-1)*rows));
innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
if (i % rows == 0)
{
innercode += '</tr><tr>';
}
}
innercode += '</tr></table>';
grid.innerHTML = innercode;
$('#container').fadeIn('slow');
}
It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":
<div id="whatever" onclick="function(this)"></div>
If you're actually more interested in getting the id of the div clicked on, you can do this:
<div id="whatever" onclick="function(this.id)"></div>
However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.
Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:
$("<div></div>")
.click(function(e) {
selectTarget(i, who);
})
.appendTo(container);