How to add an index column to a dataTables table? - javascript

I have a table which is populated using jQuery dataTables. I want to know:
How to add an index column. The dataTables.net site has an example which tells how to give a present index file the index properties not how to make it.
I want to make one of my columns a volume slider. It has only a number which is between 0-100 and want to use jQueryUI slider to make it. Where should I intialise the slider function? Before or inside of dataTables initialization function or after it, and how?

Adding an index column is covered pretty well in the online documentation here: https://datatables.net/examples/api/counter_columns.html
As for the volume slider, I did find a hack-y way to get it working. I added an empty th in the thead and a td at the beginning of each row in the tbody. The first td has the slider div and a rowspan of 3 (my example has only 3 rows). The other tds are empty with a style of display:none.
<table id="myTable" class="display">
<thead>
<tr>
<th></th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="3">
<div id="slider"></div>
</td>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<!-- Other rows here -->
</tbody>
</table>
In the JS, I used the example shown in the documentation for an index column, with several changes. I am initializing the slider on "initComplete" of the DataTable, and again when the table is sorted or searched.
var table = $("#myTable").DataTable({
//Table options here
"initComplete":function(){
$("#slider").slider(sliderOpts);
}
});
table.on('order.dt search.dt', function(){
table.column(0, {search:'applied', order:'applied'}).nodes().each(function(cell, i){
if(i == 0){
$(cell).attr("rowspan","3").html("<div id='slider'></div>").css("display","table-cell");
$("#slider").slider(sliderOpts);
} else {
cell.innerHTML = '';
$(cell).css("display","none")
}
})
}).draw();
Here is a jsfiddle of my solution: https://jsfiddle.net/r7jwv76L/2/

Related

Jquery - Add Column left or right to previous Column

I have two buttons called "Add Column Left" and "Add Column Right". I need to get the Index of the clicked cell, so that I can get the column index and add the new column to the previous one.
My current code:
function AddColumn(addLeft){ // Which button is clicked? Add Left || Add Right
var header = $('#tableHeader'); // Get the table header element
var headerContentToAppend = "<th>Header</th>"; // The default text of the new header
var table = $('#tableBody'); // Get the table body element
var rowContentToAppend = "<td>Content</td>"; // The default text of the new cells
// issue 1: missing index of the clicked/focussed column
if (addLeft) { // Button "Add Column Left" clicked
header.prepend(headerContentToAppend); // Add the Column to the left of the previous column
}
else { // Button "Add Column Right" clicked
header.append(headerContentToAppend); // Add the Column to the right of the previous column
}
$('table th').last().attr("contenteditable", true).focus(); // set all cells editable and focus the last one
table.find("tr").each(function() { // Get all existing rows ....
// issue 2: maybe the cells don't match to the right column, I have to test this after finishing the first issue
$(this).append(rowContentToAppend); // ... and add cells to the new column
});
}
So my problem is to get the right index of the clicked column. After adding a new column i have to fill it up with new cells below.
I placed two comments called "issue" in the code, that should make things clear.
My HTML Code:
<table id="dataTable">
<thead id="tableHeader">
</thead>
<tbody id="tableBody">
</tbody>
</table>
I want to control the table by Javascript to keep it dynamic.
Since you're using jQuery you could use the method index() to get the element index :
var index = $(this).closest('tr').find('td').index($(this));
Hope this helps.
var index = 0;
function AddColumn(addLeft){
var header = $('#tableHeader');
var headerContentToAppend = "<th>Header</th>";
var table = $('#tableBody');
var rowContentToAppend = "<td>Content</td>";
if (addLeft)
header.find('th').eq(index).before(headerContentToAppend);
else
header.find('th').eq(index).after(headerContentToAppend);
$('table th').attr("contenteditable", true).last().focus();
table.find("tr").each(function() {
if (addLeft)
$(this).find('td').eq(index).before(rowContentToAppend);
else
$(this).find('td').eq(index).after(rowContentToAppend);
});
$('td').removeClass('selected');
}
$('body').on('click','td',function(){
$('td').removeClass('selected');
$(this).addClass('selected');
index = $(this).closest('tr').find('td').index($(this));
});
.selected{
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead id='tableHeader'>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</thead>
<tbody id='tableBody'>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
<tr>
<td>column 11</td>
<td>column 22</td>
<td>column 33</td>
</tr>
<tr>
<td>column 111</td>
<td>column 222</td>
<td>column 333</td>
</tr>
</tbody>
</table>
<br>
<button onClick='AddColumn(true)'>< Add to the Left</button>
<button onClick='AddColumn(false)'>Add to the Right ></button>

Convert multiple tables to one table inside same DIV using jQuery

I have multiple tables inside div with same columns and I want them to convert to one table with all records from that tables.
Can it be done with jQuery?
My HTML looks like this:
<div id="multiTabels">
<table id="table1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Record 1</td>
<td>Record 2</td>
</tr>
</table>
<table id="table1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Record 3</td>
<td>Record 4</td>
</tr>
</table>
</div>
Try this :
$(function(){
var $firstTable = $('#multiTabels table:first');
$('#multiTabels table:not(:first)').each(function(){
$firstTable.append($(this).find('tr').has('td'));
$(this).remove();
});
});
JSfiddle Demo
Anything can be done with jQuery.
There's a really big thing to point out with my jsFiddle: I am using the thead and tbody tags. This is really important for segregating rows and is a semantic step forward in HTML. If you inspect tables in your dev console, you'll notice most browsers automatically add a tbody around all tr elements in a table now, so it's good to start doing this.
https://jsfiddle.net/wumztk45/
// This binds a hook to the document.
// If any 'click' events happen to an element with the id "cruch" this event fires.
// This event will persist even when crunch is deleted, and is good
// for when binding to elements that may not exist at the time.
$(document).on('click', "#crunch", function(event) {
// Find our container.
var $multiTables = $("#multiTables"),
// Find all tables in our container.
$tables = $multiTables.children("table"),
// From all tables after the first, find all <tr> elements within <tbody> elements.
$rows = $tables.not(":first").children("tbody").children("tr");
// Append these rows to the first table's tbody.
$tables.first().children("tbody").append( $rows );
// Remove the other tables.
$tables.not(":first").remove();
// Disable this button.
$(this).prop( 'disabled', true );
} );
Try this:
$(document).ready(function (){
$("#multiTabels table tr").each(function(){
$("#newTable").append($(this)); //append to any new table
});
});

Add table row with jQuery before button

I have this table, and I want to add Rows up the button, in the same rowId. For example, on clicking the Add Row 1 button, i want to add a row in row1, under "Some content 1", and so on.
<table id="table1">
<thead>
<th>Heading 1</th>
<th>Heading 2</th>
</thead>
<tbody>
<tr id="row1">
<td>Some content 1<td>
<td><button id="addButton1">Add Row 1</button><td>
</tr>
<tr id="row2">
<td>Some content 2<td>
<td><button id="addButton2">Add Row 2</button><td>
</tr>
<tbody>
</table>
This is the script I use so far:
$("#addBtn").on("click", function () {
$("#table1 tbody").append("<tr><td>1</td><td>1</td></tr>");
});
This is adding rows at the end of the table. How can I add rows in between, in the same section, using jQuery?
Try to use .closest() along with .after() to achieve what you want, and you should use id starts with selector in this context or you can add one common class for all of that buttons and use that as a selector.
$("[id^=addButton]").on("click", function () {
$(this).closest('tr').after("<tr><td>1</td><td>1</td></tr>");
});
Side Note: I have edited some of your ugly html in order to make your code valid
DEMO
You can do like this.
$("#table1 button").on("click", function () {
$(this).parents('tr').after("<tr><td>1</td><td>1</td></tr>");
});

How to get row id from row Index in table using JavaScript

Suppose this is my table:
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
How can I get row id using the row index from a table?
Above is just an example where id is static but in my case my id is dynamic, so I can't use
document.getElementById().
Assuming you have only one table on your page:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table a id, though, and get your row like this:
<table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
This way, you can be certain you don't get any interference, if you have multiple tables in your page.
"So, How can i get row id using row Index from a table"
You would select the table, and use the .rows property to get the row by index.
var table = document.getElementsByTagName("table")[0]; // first table
var secondRow = table.rows[1]; // second row
Then you just get the ID in the typical manner.
console.log(secondRow.id); // "b"
DEMO: http://jsfiddle.net/MErPk/
Answer has been edited
With CSS3 you can use the nth-child selctor. Here the example shows the rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
In jQuery you can do this with
alert($("table tr:nth-child(2)").attr('id'));
The same syntax nth-child() can be used in CSS
<style>
tr:nth-child(2) {
color: red;
}
</style>

Find cells that are not in the header and are only in the first column of a table using JQuery

I used to have something like,
$(elem).parents('li').find(...)
Where elem was an item in a list, so it was easy to get a reference to all of the items in the list. Now however I have added more information and decided to use a table, where the list fits into the table as follows.
[header][header][header]
[list 1][ cell ][ cell ]
[list 2][ cell ][ cell ]
[list 3][ cell ][ cell ]
I'm a little stuck creating the equivalent JQuery do a .find() on just the cells that have the list items in it. The list items are always in the left-most table cells excluding the header.
Here is what the table looks like in html.
<table id="my-table">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
<tr>
<td>list item 1</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
<tr>
<td>list item 2</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
</table>
Use:
$(elem).closest('tr').find(...)
If the li's are always in the first cell of each row then this should work:
$('td:first-child>li')
If you make use of thead and tbody you can find rows only in the body much easier.
Change your markup to something like this:
<table>
<thead>
... header rows ...
</thead>
<tbody>
... body rows ...
</tbody>
</table>
Then you can simply include tbody in your jquery selector to find just rows which are body rows.
Something like #my-table tbody td:first-child. Where first-child will get you the first column.
This will give you only the first column in each row.
var rows = $('tr :nth-child(1)', '#my-table').not('th');
If you want to loop through and do something to each of these now, just use:
rows.each(function()
{
//Do something with the columnn
});
The solution below will output the matching elements, first <td> in each row, to <div id="#results"
Working example at: http://jsfiddle.net/6faUf/
HTML:
<table border="5">
<thead>
<tr><th>1</th><th>2</th><th>3</th></tr>
</thead>
<tbody>
<tr><td><ul><li>List1</li></ul></td><td>2</td><td>3</td></tr>
<tr><td><ul><li>List2</li></ul></td><td>2</td><td>3</td></tr>
</tbody>
</table>
<div id="results">The list values are: </div>
JavaScript (jQuery):
$('td:first-child').each(function(){
var value = $(this).text();
$("#results").append(value);
});
If you need the cells that have the list items in them, you'd need the :has() selector, so there'd be something like that:
$(elem).closest('table').find('td:has(li) ...') — if you need all the li in the table
or $(elem).closest('tr').find('td:has(li) ...') — if you need all the li in the raw

Categories