I have a table as follows:
<table>
<tr>
<td>col 1</td><td>col2</td>
</tr>
<tr id="insert">
<td>field</td><td>Field 2</td>
</tr>
<tr>
<td>another field</td><td>one more field</td>
</tr>
</table>
Now the issue is that I need to dynamically insert new rows AFTER the middle row (id = insert). I have a custom javascript function to insert elementsAFTER an element by using an insertBefore call on the next element.
The new rows create successfully using the following javascript:
var new_row = document.createElement('tr');
new_row.innerHTML="<td>test</td>";
insertAfter(document.getElementById("insert"), new_row);
However, the new row refuses to accept any simple html formatting using the innerHTML. The final output of the new row looks something like:
<tr>test</tr>
You see it doesn't want to output the I have specified. The actual script is a lot more complex and so unfortunately manually adding each using an appendChild or similar function would be far too time consuming and probably rather resource intensive. Is there anyway I can just add a 'chunk of html' to this table row and in this chunk define the table columns?
I'm baffled, any help is MUCH appreciated.
You can use the native insertCell() method to insert cells.
Give this a try:
Example: http://jsfiddle.net/VzTJa/
var new_row = document.createElement('tr');
new_row.insertCell(0).innerHTML = "test";
new_row.insertCell(1).innerHTML = "test2";
or you can accomplish it without your insertAfter() function by using insertRow() as well.
Example: http://jsfiddle.net/VzTJa/1/
var insert = document.getElementById("insert");
var new_row = insert.parentNode.insertRow( insert.rowIndex + 1 );
new_row.insertCell(0).innerHTML = "test";
new_row.insertCell(1).innerHTML = "test2";
Give this workaround a try:
Example: http://jsfiddle.net/VzTJa/2/
var temp = '<table><tbody><tr>';
var close_temp = '</tr></tbody></table>';
var temp_div = document.createElement('div');
var html_to_insert = '<td>tester</td><td>tester</td>';
temp_div.innerHTML = temp + html_to_insert + close_temp;
insertAfter(document.getElementById("insert"), temp_div.firstChild.firstChild.firstChild);
temp_div.removeChild(temp_div.firstChild);
Basically creates a couple strings representing the opening and closing tags of a table. You concatenate it with your content, and set it as the innerHTMl of a temporary div, then fetch the row you want, and do an .appendChild().
There may be a better way, or you may find a way to improve this one.
I came up with this after glancing at a solution in this article from a guy who apparently worked on IE and is partly responsible for the parser.
If you can use jQuery, try the append method from it. jQuery append reference
If you do find performance to be an issue, you might find an improvement by building up the dynamic DOM you want to add in javascript before appending it to the actual HTML DOM element that will make it visible. This will keep your number of repaints to a minimum.
Related
I have a table that will be populated with data and I need to be able to pull data from specific cells using the cell ID. I have tried using document.getElementById("idName").value but I have now come to understand that the .value is only used with <input> tags. I need the JavaScript code to get the data from the <td> tag, using the ID, and not by hard coding in the information that is in the table as the information will change in that cell.
EDIT: Here is the JavaScript code
'
var RNNo5a = document.getElementById("RN5.5").innerText;
var RNNo5 = document.getElementById("RbR4.4").innerHTML;
var RNN04a = document.getElementById("RN6.4").innerHTML;
//var test;
//if (RNNo5a == RNNo5) {test = RNN04a;}
alert(RNNo5a);
`
The table is filled out by another JavaScript code... could that be the source of my problem?
Try using getElementsById("IdName").innerHTML
The innerHTML property sets or returns the HTML content (inner HTML) of an element.
You can read more on innerHTML here
EDIT RE OP's comment - It works in the below example.
var x = document.getElementById("test").innerHTML;
alert(x);
<p id="test">Hello, World!</p>
I'm trying to make a barcode scanner and I have a problem when some product doesn't exist it creates a new array with JavaScript and sends the problem to the that table. My problem is that I can't edit the table with innerHTML
JavaScript Function:
var table = document.getElementById("listViewTable");
var tableF = document.getElementById("listTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var td1 = document.createElement("td");
//row.innerHTML = '(A few <td> and an <input>)';
td1.innerHTML = '(More <td> and another <input>)';
row.appendChild(td1);
row.className = "tableCell newSKU";
That commented line row.innerhtml is what I tried to achieve but I.E does not support it.
This should be the end result:
The last product in yellow can't be put in the same table and as such does not have the same style as the others.
From ppk's guide to browser quirks:
In IE9 and lower innerHTML refuses to work on tables and selects. Solve this by using pure DOM methods instead. See this explanation of the table behaviour by innerHTML’s inventor. I assume something similar goes for selects.
Use createElement, appendChild and friends to create the cells.
code in html file is as following:
<html>
<script type="text/javascript">
var records=[{"name":"Fred","id":"123"},{"name":"Jim","id":"456"}];
</script>
<table id="tb1">
<tr id="row1">
<td style="background-color:gray" id="name">name</td><td style="background-color:gray" id="id">id</td>
</tr>
<tr id="row2"><td>shouldn't be added here</td><td>neither here</td></tr>
</table>
</html>
I want to add the contents of records between row1 and row2 in pure javascript.(without any third party javascript framework) What should I do?
You don't add to "tags," you add to elements.
In the general case, you create elements via document.createElement (or by assigning a string containing HTML to an existing element's innerHTML property).
You add elements as children of other elements using appendChild or insertBefore.
So for instance, here's how you could add a row containing two table cells before the id="row2" in your table:
var newRow = document.createElement('tr');
newRow.appendChild(document.createElement('td')); // The first cell
newRow.appendChild(document.createElement('td')); // The second cell
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2); // Insert it
However, as Heitor points out, for tables there are specific methods you can use instead which are a bit less verbose:
insertRow on table and tbody/thead elements
insertCell on row elements
Here's the code above using insertCell:
var newRow = document.createElement('tr');
newRow.insertCell(-1); // The first cell
newRow.insertCell(-1); // The second cell
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2); // Insert it
We could also use insertRow:
var row2 = document.getElementById("row2"); // Get existing row
var newRow = row2.parentNode.insertRow(row2.rowIndex); // Create and insert new row
newRow.insertCell(); // The first cell
newRow.insertCell(); // The second cell
...but then we'd be making changes to the displayed DOM repeatedly (adding a blank row, then adding a cell, then adding another cell), which is better avoided if possible. In the first two examples, we created the row and added its cells before adding that whole structure to the DOM, performing one live DOM manipulation.
The DOM API can be verbose and a bit awkward, and implementations of it can vary a bit browser to browser (though all of the above is reliable). You obviously can use it directly, but you can also use any of several good JavaScript DOM manipulation libraries to get some browser compatibility stuff sorted out for you, and to get a lot of useful utility functionality.
Use insertRow method, clean and precise!
var row = table.insertRow(0); // to insert in the top OR
var row = table.insertRow(N); // to insert in the (N+1)-th line of the table OR
var row = table.insertRow(-1); // to insert in the bottom
I have html table in a var and need to sum each row and put total in the last cell, and put the result back to the var (I need it for further programming for SharePoint). The table has fixed rows and TDs. JS or Jquery is fine. any Ideas. thank you
here is the var:
var A1='<table Id="AEid" width="85%" border="3"><tbody>
<tr><th><b>AM1</b></th><th><b>AM2</b></th><th><b>Total</b></th>
</tr><tr><td rowspan="1"></td><td rowspan="1"></td><td rowspan="1"></td></tr>
<tr><td rowspan="1"></td><td rowspan="1"></td><td rowspan="1"></td></tr></tbody></table>';
You can just create jquery object from your var without attaching to the DOM and manipulate it to heart's content.
var newText ='<table><tbody><tr><td>1</td><td>2</td><td></td></tr><tr><td>1</td><td>2</td><td></td></tr></tbody></table>';
$newDiv = $(newText);
You can refer to the jsfiddle I made. Not the best answer, but will do what you need http://jsfiddle.net/j5pKx/4/. Hope that helps
The problem I'm having is that when I try to create a table via javascript, it is closing the table before I actually give the closing tag.
I'm using this solution to record/read cookies
https://stackoverflow.com/a/1960049
What I needed was to make a wishlist from this "array" of cookies, by looping through them all and putting them into a table. (inside the #catalog div)
function loopArray() {
var cookie = $.cookie("testCookie");
var items = cookie ? cookie.split(/,/) : new Array();
$('#catalog').empty();
$('#catalog').append("<table><tr><th>Part #</th><th>Delete</th></tr>");
for(var i=0;i<items.length;i++){
$('#catalog').append("<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>");
}
$('#catalog').append("</table>");
}
Not sure why this won't work. Tried cheating with innerHTML but that gave me problems, and I tried using document.write but when using the remNum function to remove the cookie value and refresh the list it completely wipes my whole page out.
This is what my table ends up looking like when I take out the code
<table><tbody><tr><th>Part #</th><th>Delete</th></tr></tbody></table><tr><td width="150">three</td><td><img src="searchAssets/img/delete.png"></td></tr>
You can't add partial mal-formed pieces of HTML with .append(). You have to add fully formed pieces of HTML. This line line $('#catalog').append("<table><tr><th>Part #</th><th>Delete</th></tr>"); is a real problem as it's only a piece of valid HTML and is invalid by itself.
What you can do is accumulate the string of partial HTML in your loop and just append the finished string once to the DOM at the end.
Or, you can add the fully formed HTML for the table, but with no rows and then insert a complete row at a time in your loop.
What you cannot do is append <table>, then some rows and then append </table> at the end. append creates WHOLE HTML objects so append <table> challenges the browser to make an entire object out of it or reject the whole thing.
For example, you can do it like this:
function loopArray() {
var cookie = $.cookie("testCookie");
var items = cookie ? cookie.split(/,/) : new Array();
var html = "<table><tr><th>Part #</th><th>Delete</th></tr>";
for(var i=0;i<items.length;i++){
html += "<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>";
}
html += "</table>";
$('#catalog').html(html);
}
What you are doing is wrong. .append doesn't work that way. You need to have the complete tag inside append, not partial content.
In your case I would suggest you put them as a string and append it at the end. See below,
$('#catalog').empty();
var tableContent = [];
tableContent.push("<table><tr><th>Part #</th><th>Delete</th></tr>");
for(var i=0;i<items.length;i++){
tableContent.push("<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>");
}
tableContent.push("</table>");
$('#catalog').html(tableContent.join('')); //using .html as you had it emptied earlier.