What is the best method in jQuery to add an additional row to a table as the first row?
I have a table like this
<table id="mytable" cellpadding="0" cellspacing="0">
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
</table>
<button id="but">mybutton</button>
I want to add a row as the first row to the beginning of the table with given default values. How can I accomplish this using JavaScript and jQuery? A fiddle will be helpful.
You can use .prepend function in jQuery.
$('#mytable').prepend($('<tr>'));
http://api.jquery.com/prepend/
http://jsfiddle.net/32Ymw/
$("#but").click(function(){
row = $("<tr></tr>");
col1 = $("<td>col1</td>");
col2 = $("<td>col2</td>");
col3 = $("<td>col3</td>");
row.append(col1,col2,col3).prependTo("#mytable");
});
Using .on('click',...); and prepend:
http://jsfiddle.net/k8hCa/
jQuery:
$('#but').on('click', function(e){
$('#mytable').prepend('<tr><td>newcol1</td><td>newcol2</td><td>newcol3</td></tr>');
});
The accepted answer is good, but it is definitely worth noting that the tbody is the node you should append/prepend to, and using the appendTo and prependTo methods is the best solution as it will work when there are any number of rows, including zero.
See this answer for a good example: https://stackoverflow.com/a/1353736/2812428
Note also that it is good practice to specify a tbody yourself, even if there are no rows, to avoid the issue that there would be no tbody automatically in the DOM in the case that there were no rows added to the table.
The jQuery .prepend() method should work
$('#mytable').prepend($('<tr>'));
Folloing is what I am doing
Template
<script type="text/template" id="cardTemplate">
<TR class=Normal>
<TD>
{0}
</TD>
<TD>
{1}
</TD>
<TD>
{2}
</TD>
</TR>
</script>
jQuery
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
var cardTemplate = $("#cardTemplate").html();
//Note: format is a custom method added for "String"
var template = cardTemplate.format("a", "b","c");
//$('#tblScanResult tbody > tr:first').before(template);
$('#tblScanResult tbody').prepend(template);
This question is really ancient but just for the sake of completeness, if you have headers, you can easily modify Alex answer to insert at the top of the body rows but after the headers rows thusly...
<table id="mytable" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
</tbody>
</table>
<button id="but">mybutton</button>
$('#but').on('click', function(e){
$('#mytable > tbody').prepend('<tr><td>newcol1</td><td>newcol2</td><td>newcol3</td></tr>');
});
Related
I tried to use cloneNode mentionned here Copy the content of one table into another but Chrome says cloneNode is not a function
https://jsfiddle.net/4wczdykc/1/
<table>
<thead>
<tr>
<th scope="col" colspan="1">TABLE TO CLONE</th>
</tr>
<tr>
<th>Column</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
script:
myTable = document.getElementsByTagName("Table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
The getElementsByTagName() method accesses all elements with the specified tagname.So you have to select the first element of the NodeList. So passed [0] to select it.
myTable = document.getElementsByTagName("table")[0];
myClone = myTable.cloneNode(true);
document.body.appendChild(myClone);
WORKING FIDDLE
I have a table with thead with first th colspan = 1. I want to set it programmatically to value 2 : it doesn't work, how to do this ?
Here's source code :
https://jsfiddle.net/Lgof8m6q/
<table>
<thead>
<tr>
<th scope="col" colspan="1">TITLE</th>
</tr>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
javascript :
var myTable = document.getElementsByTagName('table')[0];
var myThead = myTable.getElementsByTagName('thead')[0];
_tr = myThead.getElementsByTagName("TR")[0];
_th = _tr.getElementsByTagName("TH")[0];
_th.colspan = 2;
It's colSpan, not colspan ;-)
See colSpan documentation.
(updated fiddle).
Javascript DOM elements has a special method for setting attributes, which is setAttribute('<attribute>','<value>')
_th.setAttribute("colspan", "2");
check this fiddle:
https://jsfiddle.net/Lgof8m6q/7/
I have a table structure like this. Fairly simple one.
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
At runtime I am binding a new row to this table for a particular rowclick. This new row contains a new table.
Now on clicking the row again, I want to be able to remove the newly added row(the new table).
I am using bootstrap table.
Here is what I have tried so far.
$('#myTable').on('click-row.bs.table', function (e, row, $element) {
//if ($element.has('#newlyAddedTable').length) { ....// did not work
if ($('#myTable').has('#newlyAddedTable').length) { // this removes the table on any row click. Not what I intend to do
{
$("#newlyAddedTable").remove();
} else {
// some operation...
}
}
I want to be able to remove the newly added table on the row it was created.
Just more explanation based on the Answers below:
<tr> ----------> if i click this
<td>
<table id="newlyAddedTable"> ---------> this is added
</table>
</td>
</tr>
<tr> ----------> if i again click this or maybe any other row in the table
<td>
<table id="newlyAddedTable"> ---------> this is removed
</table>
</td>
</tr>
Update: from OP's comment below it sounds like the best way to implement the new table is to use a class selector and not an id selector. The code below has been updated accordingly. ***Where previously there was an id for newTable there is a class ---> #newTable ===> .newTable:
Just change:
$('#myTable').has('#newlyAddedTable').length
To:
$('.newlyAddedTable', $element).length //element === clicked row -- see demo
vvvvv DEMO vvvvv
$('#myTable').bootstrapTable().on('click-row.bs.table', function(e, row, $element) {
if( $('.newTable', $element).length ) {
$('.newTable', $element).remove();
} else {
$('td:first', $element)
.append( '<table class="newTable"><tr><td>NEW TABLE</td></tr></table>' );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.css" rel="stylesheet"/>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
Try replacing your remove code with this:
$(document).on("click", "#newlyAddedTable", function(){
$(this).remove();
});
The code above registers a click listener on the document. The second parameter filters those events for those with the target #newlyAddedTable. This way you don't have to register a new click handler every time you insert a row (as in #VimalanJayaGanesh's solution).
P.S. If you are adding HTML that looks like this:
<tr>
<td>
<table id="newlyAddedTable">
</table>
</td>
</tr>
Then you are probably actually wanting to remove the parent tr (not the table with the id). There are two ways to fix this.
You can change the selector that filters click events and so have the tr handle the click rather than the table element in my example code:
$(document).on("click", "tr:has(#newlyAddedTable)", function(){
You can leave the selector as is but grab the parent tr from the table and remove that changing the remove line above to:
$(this).parents("tr").first().remove()
or
$(this).parent().parent().remove()
As I don't have your complete code / fiddler, here is a possible solution.
Are you looking for something like this?
$('#add').on('click', function()
{
var newRow = '<tr CLASS="newrow"><td colspan="3"><table><tr><td>Test</td><td>User</td><td>test#example.com</td></table></td></tr>'
$('#myTableBody').append(newRow);
Remove()
});
function Remove()
{
$('.newrow').off('click').on('click', function()
{
$(this).remove();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTableBody">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
<button type='button' id='add'>Add</button>
Note:
The following line indicates that,
$('.newrow').off('click').on('click', function()
the click event will be binded to the new row only once.
The reason for adding 'off('click') is, when you are dynamically adding rows (with common class 'newrow') to the table, the events will be binded several times. To avoid that, remove the previously binded click event and add a new one.
Here I have a table
<table id="table">
<thead>
<tr>
<th>Name</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<tr style="display:none">
<td>jones</td>
<td>.net</td>
</tr>
<tr style="display:none">
<td>James</td>
<td>SAP</td>
</tr>
<tr>
<td>Charles</td>
<td>Java</td>
</tr>
</tbody>
</table>
I want to get text of first row first td text which are visible using jquery, by
above table, I want result as "Charles".
How can get it. I have tried like
$("#table").closest('tbody').children('tr:first').find('td:first').text()
but not getting result.how can I?
Try to use :visible selector to get the visible rows,
$("#table tbody tr:visible:first td:first").text()
To get the visible one use the according :visible selector that jquery ships:
$('#table > tbody > tr:visible:first > td:first').text();
This is Worked for Me.
$('#table> tbody > tr:visible').first().find('td').first().text();
I have an HTML table that I'm sorting with jQuery tablesorter. I have an external link that sorts the table by name using JavaScript. Within that JavaScript function though, I have to say sort by column 0 instead of just saying sort by the name column.
How can I modify what I have below so I don't have to remember that name is column 0 in JavaScript?
$('document').ready(function(){
$('table#classes_table').tablesorter();
$("#sort-link").click(function() {
//How can I say something like sort by "Name" instead of having to remember name is column 0
var sorting = [[0,0]
$("table").trigger("sorton",[sorting]);
return false;
});
});
Sort by name<br><br>
<table class="tablesorter" id="classes_table">
<thead>
<tr>
<th>Name</th>
<th>School</th>
<th>Students</th>
</tr>
</thead>
<tbody>
<tr>
<td>Class1</td>
<td>School5 </td>
<td>32</td>
</tr>
<tr>
<td>Class2</td>
<td>School1</td>
<td>7</td>
</tr>
</tbody>
</table>
You could use a hack...
var columnIndex = $('table > thead > tr > th:contains("Name")').index();