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
Related
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 a standard HTML formatted table, that dynamically generates the content, via Zend Framework. From which I have an issue altering the form internally PHP side. So I need to alter the tables appearance somehow. With that on the occasion I have an element show up in one of the rows and when this element shows up I want to break out of the table and then do something after it then start the table again.
Basically I want to inject the equivlant of
</tbody></table>/*other stuff*/<table><tbody> after the row containing the one element I seek which in this case is a label.
I tried $("label[for='theLable']").parents('tr').after('</tbody></table><br><table><tbody>') which appears to ignore the ending table parts add the br, and then does a complete open/close tag for table and tbody within the same table I am trying to break out of so inbetween tr tags basically it adds this new table
Whats the best way to approach this concept?
update with jsfiddle link
http://jsfiddle.net/cPWDh/
You can't really modify the HTML of the document the way you're thinking, since it's not a legitimate way to alter the DOM.
Instead, I would create a new table and .append the rows you want to move to it, which will automatically move them from their current location (instead of copying them):
$(document).ready(function() {
var $trow = $('label[for="specialLabel"]').closest('tr'),
$table = $trow.closest('table');
$('<table>').append( $trow.nextAll().andSelf() ).insertAfter($table);
});
http://jsfiddle.net/cPWDh/1/
this approach won't work in js. What you could do if the table has not too many rows is this:
var nextTable = $("table").after("/*other stuff*/<table id="nextTable"></table>");
//now you loop over the lines of your original table that you want to have after the "break", and move them to the nextTable:
var before = true;
$("table tr").each(function(){
if ($(this).has("[for='theLable']")) {
before = false;
}
if (!before) {
nextTable.append($(this));
}
});
In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>
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.
How do I append a row to a table using the prototype library.
This is part of a form so I would like to also find a way to increment the <input name="container[0]"> value. Is this possible?
if i understand you right something like this would work:
var numrows = $$('#tableid tr').length;
$('tableRow').insert({after:'<tr><td><input type="text" name="container['+numrows+']"></td></tr>'});
if you can provide more details then i'll be able to help out a bit more