jQuery Modification of dynamically generated HTML Table - javascript

I have the following table
<table id="edit_po_table">
<thead>
<tr>
<th>Discount</th>
<th>
<select id="discount">
<option value="0">0%</option>
<option value="25">25%</option>
<option value="35">35%</option>
<option value="42">42%</option>
<option value="50">50%</option>
</select>
</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<th>Quantity</th>
<th>Stock #</th>
<th>Product Name</th>
<th>Volume Points</th>
<th>Price</th>
<th>Volume Total</th>
<th>Line Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the following jQuery code
$('#table_po_product_list :checkbox').click(function() {
if($("#table_po_product_list :checkbox").prop('checked')) {
var i = $("#table_po_product_list input:checked").length;
$('#bottom-menu span').html(i + (i != 1 ? " items" : " item"));
} else {
var i = $("#table_po_product_list input:checked").length;
$('#bottom-menu span').html(i + (i != 1 ? " items" : " item"));
}
var stocknos = $('#table_po_product_list :checked').map(function(){
return $(this).val();
}).get().join(',');
if($('#table_po_product_list :checked').length === 0) {
$('#edit_po_table tbody').html('');
}
alert(stocknos);
if (stocknos.length > 0) {
$.ajax({
type: "POST",
url: "functions.php",
data: "ids=" + stocknos, //{'stock_nos[]': stocknos},
cache: false,
success: function(html) {
$('#edit_po_table tbody').html(html);
}
});
}
})
$('#edit_po_table tbody input').on("change", function(event){
var tdid = $(this).attr('id');
var qty = $('#edit_po_table tbody tr#'+tdid+' td input').val();
var vol = $('#edit_po_table tbody tr#'+tdid+' td#vol_pts').text();
var price = $('#edit_po_table tbody tr#'+tdid+' td#price').text();
alert(tdid);
$('#edit_po_table tbody tr#'+tdid+' td#total_vol').html(qty*vol);
$('#edit_po_table tbody tr#'+tdid+' td#total_price').html(qty*price);
})
And functions.php will return the following when asked:
<tr id=0141>
<td><input type="text" size="5"></td>
<td>0141</td>
<td>Formula</td>
<td id="vol_pts">23.95</td>
<td id="price">68.49</td>
<td id="total_vol"></td>
<td id="total_price"></td>
</tr>
<tr id=6424>
<td><input type="text" size="5"></td>
<td>6424</td>
<td>Reference Guide (Bilingual)</td>
<td id="vol_pts">0.00</td>
<td id="price">9.20</td>
<td id="total_vol"></td>
<td id="total_price"></td>
</tr>
Now, I am trying to get my $('#edit_po_table tbody input').on("change", function(event) jquery section of code to work but am unable to find a way to make it work.
Basically, this is how I want my code to function, the user is shown a product table, they then select products from the table. The selection gets passed via jquery to functions.php which then spits back the <tbody> data for the edit_po_table.
Then user then needs to fill in the quantity desired, and the table should auto calculate the total volume points and price for the line. i have tried different ways to get the <tr> id, then go to the <td> it only works for the first row, I can't get it to work for any other rows.
Help?

You can try after modifying the jQuery.on to this
$('#edit_po_table tbody').on("change",'input', function(event){
//your code
});
This syntax is equivalent to $.live and event binding will persist for dynamically added elements too. :)

Related

table row as a counter in HTML

I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>

Refresh div after delete table row

I can successfully delete rows of my table and remove it from the table with jquery and ajax. On top of my table i have the number of rows displayed. How can i refresh the div (update_count) to show the decremented number after deleting ?
<div id="update_count"><?=$num_count?> data</i></div>
<table class="table">
<tr>
<th style="width:1px"><strong>Date</strong></th>
<th style="width:5px">Labo</th>
<th style="width:5px">Delete</th>
<tr>
<?php foreach($IndicacionesLab as $row)
{
?>
<tr>
<td><?=$row->insert_time;?></td>
<td><?=$row->laboratory;?></td>
<td> <a title="Eliminar laboratorio <?=$row->laboratory;?>" class="st deletelab" id="<?=$row->id_lab; ?>" style="background:rgb(223,0,0);cursor:pointer">Delete</a></td>
</tr>
<?php
}
?>
</table>
Js
$(".deletelab").click(function(){
if (confirm("Sure to delete ?"))
{
var el = this;
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'<?=base_url('admin/DeleteHistLab')?>',
data: {id : del_id},
success:function(response) {
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
}
})
For simplicity keep all the data rows in a <tbody>
<table id="my-table">
<thead>
<tr>
<th> heading 1 </th>
</tr>
</thead>
<tbody>
<tr>
<th> data 1 </th>
</tr>
</tbody>
</table>
Then after you remove the row get the length of all rows remaining
$('#update_count').text( $('#my-table tbody tr').length + ' Items')

JQuery: search and filter a table by a single column

I want to search a table by the values in a single column.
The table looks like this:
<table class="table main-content">
<thead>
<td><b>Title</b></td>
<td><b>Name</b></td>
<td><b>State (D)</b></td>
<td><b>Party</b></td>
<td><b>Room</b></td>
<td><b>Phone #</b></td>
<td><b>Special Role(s)</b></td>
</thead>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
...
I want to be able to search the table by a given column, say names (index 1) or state (index 2). I've tried jets.js but it only allows one instance per page while I require at least two. JQuery is preferred, JS is fine, and external libs are ok but not optimal.
Cheers!
Edit:
I've tried using the following:
var $rows = $('#congress tr');
$('#stateSearch').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
The above code searches all of the columns in the table. How can I adjust it to search only for a specific column? (By index.)
The goal is to hide all of the tr that don't match the query in the given column
Something like this
function isFound(name, state)
{
$("table tbody").find("tr").each (function(){
var trElem = $(this);
if (($(this).find("td:eq(1) a").text() == name) && ($(this).find("td:eq(2)").text() == state))
return trElem;
})
return false;
}
Usage:
if (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
or, if you have more than one elements, use a loop for removing
while (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
Here's an example that will hide all rows where the State column (index 3) is TN. You can adapt it as you need:
$('td:nth-child(3)').each (function(){
if( $(this).val() == 'TN' )
$(this).parent().hide();
});
Another easy solution would be to use Datatables, which have a built-in search feature and methods to search by column. It may be overkill for your project, but take a look anyway for the future.
DataTables Example
You could reinvent the wheel, but it's probably better to just use DataTables unless you have an expressed need to do otherwise:
var $table = $('table');
// Setup - add a text input to each footer cell
$table.find('tfoot th').filter(':eq(1),:eq(2)').css('visibility', 'visible').each(function() {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
// DataTable
var table = $table.DataTable({
lengthChange: false
});
// Apply the search
table.columns().every(function() {
var col = this;
$('input', this.footer()).on('keyup change', function() {
if (col.search() !== this.value)
col.search(this.value).draw();
});
});
table tfoot tr th {
visibility: hidden;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.js"></script>
<table class="table table-striped main-content">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</tfoot>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
</tbody>
</table>
try this:
var text = $(this).find('td:eq(1),td:eq(2)').text().replace(/\s+/g, ' ').toLowerCase();

Footables column sorting is duplicating rows in table, Why?

I am adding footables to a table but the table has to have a tbody for each row. This is because I am adding footable sorting and filtering to an existing system that generates the html this way.
It seems to be causing the column sorting at the to be duplicating the table rows each time you try to sort the table by column heading and I cant see why.
The table structure is kinda like this:
<table data-filter="#filter" class="footable table demo">
<thead>
<tr>
<th>Name</th>
<th>Job Title</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<td>Job Title1</td>
<td>Active</td>
<td>Description1</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Name2</td>
<td>Job Title2</td>
<td>Disabled</td>
<td>Description2</td>
</tr>
</tbody>
</table>
javascript:
$(function () {
$("table").footable().bind("footable_filtering", function (e) {
var selected = $(".filter-status").find(":selected").text();
if (selected && selected.length > 0) {
e.filter += (e.filter && e.filter.length > 0) ? " " + selected : selected;
e.clear = !e.filter;
}
});
$(".clear-filter").click(function (e) {
e.preventDefault();
$(".filter-status").val("");
$("table.demo").trigger("footable_clear_filter");
});
$(".filter-status").change(function (e) {
e.preventDefault();
$("table.demo").trigger("footable_filter", {
filter: $("#filter").val()
});
});
});
I have also set up a working jsfiddle that demonstrates the issue:https://jsfiddle.net/35ht6kup/9/
Anybody have any idea how to resolve this?
You could rebuild the table with jQuery, example (to be refined with a better selector than 'table'):
$(document).ready(function(){
var thead = $('table thead');
var tbodyhtml;
$('table tbody').each(function(){
tbodyhtml += $(this).html();
});
$('table').html(thead);
$('table').append('<tbody>'+tbodyhtml+'</tbody>');
});

Modifying javascript table to search for specific data

The search form I'm using is found here: http://bootsnipp.com/snippets/featured/js-table-filter-simple-insensitive
I found a nice js search form created by Cyruxx that I am implementing on my site. Is it possible to modify this code to only search specific table headers?
For example I have:
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
</thead>
<tbody>
<tr>
<td>107</td>
<td>John Doe</td>
<td>1074 example street</td>
</tr>
<tr>
<td>100</td>
<td>Henry</td>
<td>1111 example ave</td>
</tr>
</tbody>
</table>
How can I modify the code to only search the id column for example. In other words, typing the number '1' would only show table rows with a '1' in the 'id' header. Typing '1074' in my example would return 0 results while typing '1' would show both listings.
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
//something is entered in search form
$('#system-search').keyup( function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
$('.search-sf').remove();
tableRowsClass.each( function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if(inputText != '')
{
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
}
else
{
$('.search-query-sf').remove();
}
if( rowText.indexOf( inputText ) == -1 )
{
//hide rows
tableRowsClass.eq(i).hide();
}
else
{
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if(tableRowsClass.children(':visible').length == 0)
{
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
});
First of all - that's not great search code, its not terribly preformant and mixes view and model concerns in a way that might get difficult to maintain. I would recommend using a pre-build widget, rather than copy-pasting code that you don't understand from blogs (or wherever).
To answer your question though, you can simply constrain which columns are searchable with a css class, and use that class as a search filter:
so change
var rowText = $(val).text().toLowerCase();
to
var rowText = $(val).find('.searchable').text().toLowerCase();
and then tag everything that you want to be searchable:
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
</thead>
<tbody>
<tr>
<td class="searchable">107</td>
<td>John Doe</td>
<td>1074 example street</td>
</tr>
<tr>
<td class="searchable">100</td>
<td>Henry</td>
<td>1111 example ave</td>
</tr>
</tbody>
</table>

Categories