Display All Table Rows that are Checked - javascript

I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
I originally bring in the top 100 rows to keep the info light for the user. I also have a search functionality where the user can search for specific rows. While you can maneuver throughout different searches and still keep all of the checkboxes checked with session storage, when you hit "Checkout" it only displays the table rows that are checked and currently visible on the page. So, if I searched for a table row and checked it, but then went back to the original top 100 rows by clicking home, then that row would not display on the email.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
HTML:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
JavaScript for keeping checked checkboxes, checked, throughout the session:
$(function(){
$(':checkbox').each(function() {
var $el = $(this);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});
$('input:checkbox').on('change', function() {
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
JavaScript that brings in data from table to email:
function sendMail() {
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
$('table tr input[name="check"]:checked').each(function(){
var current_tr = $(this).parent().parent();
var data = current_tr.find('.loc').data('loc');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.rp-code').data('rp-code');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.sku').data('sku');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.special-id').data('special-id');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.description').data('description');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.quantity').data('quantity');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.unit').data('unit');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.spinner').data('spinner');
body += encodeURIComponent(data) + '\xa0\xa0';
body += '%0D%0A';
});
body += '';
link += body;
console.log(link);
window.location.href = link;
}

Revised based your comments/new code:
Even with your new pasted code, the issue still remains that you can only output whats currently available on screen due looping over the table rows. Instead you need to take it a step further and build objects to house the information you need for building your email, then place those objects in storage for later retrieval.
Again looking at your code your checkboxes have a prefix of "check-id".
$('input:checkbox').on('change', function() {
var $el = $(this);
var key = $el.prop('id');
var rowObject = {};
//check if already in storage
if(sessionStorage.getItem(key) !== null){
rowObject = JSON.parse(sessionStorage.getItem(key));
rowObject.checkedVal = $el.is(':checked'); //update it's check value
}else{
//build entire row object
var current_tr = $(this).parent().parent();
rowObject.loc = current_tr.find('.loc').data('loc');
rowObject.rpCode = current_tr.find('.loc').data('rp-code');
rowObject.sku = current_tr.find('.loc').data('sku');
//etc. as many pieces as you need
}
//set to session
sessionStorage.setItem(key, JSON.stringify(rowObject));
});
//then later for your send email method
function sendEmail(){
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
//loop over the row objects instead
$.each(sessionStorage, function(key, value){
//sort out the ones we want
if(key.indexOf("checkid-") > -1){
var rowObject = JSON.parse(sessionStorage.getItem(key));
body += encodeURIComponent(rowObject.loc + '\xa0\xa0');
body += encodeURIComponent(rowObject.rpCode + '\xa0\xa0');
body += encodeURIComponent(rowObject.sku + '\xa0\xa0');
//etc. as many pieces as you need
body += '%0D%0A';
}
});
//whatever other logic you have
}
I haven't fully tested this code for your purposes but you get the idea, build your objects then use those during your iteration.

Related

Unable to store particular target values in jQuery

$(document).ready(e => {
$(".test").click(e => {
textvalue = displayData(e);
console.log(textvalue); //prints the array
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Email</th>
<th>Contact</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>DummyName</td>
<td>20</td>
<td>Female</td>
<td>DummyEmail</td>
<td>DummyContact</td>
<td>DummyDepartment</td>
<td class="test">Click</td>
</tr>
<tr>
<td>DummyName2</td>
<td>22</td>
<td>Female</td>
<td>DummyEmail2</td>
<td>DummyContact2</td>
<td>DummyDepartment2</td>
<td class="test">Click</td>
</tr>
</tbody>
</table>
</body>
</html>
I'm using jQuery to update onscreen values in a form. Complete beginner at this.
$(document).ready(e =>{
$(".btnedit").click(e =>{
textvalues = displayData(e);
let sname = $("input[name*='name_type");
let sage = $("input[name*='age_type");
let sgender = $("input[name*='gender_type");
let semail = $("input[name*='email_type");
let scontact = $("input[name*='contact_type");
let sdept = $("input[name*='dept_type");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
semail.val(textvalues[3]);
scontact.val(textvalues[4]);
sdept.val(textvalues[5]);
});
});
function displayData(e){
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for(const value of td){
if(value.dataset.name == e.target.dataset.name)
{
//console.log(value);
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
I need to get the data stored in a table onto the inputs of the form, in order for the user to update it further. The user clicks on a record to edit it(which is displayed on the page).
The record values are stored in the array textvalues. Problem is the entire table values get stored in the array instead of just the single record.
In value.dataset.name, name is a column from the table which I'm using as the primary key (I know it's wrong, but just going with it for now).
Edit: Original table code:
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['name'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['age'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['gender'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['email'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['contact'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['department'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><i class="fas fa-edit btnedit"></i></td>
</tr>
<?php
}
Your code works fine except one little thing: all your input selectors lack closing quote and bracket, e.g. this is wrong (jQuery 3.3.1 throws error):
let sname = $("input[name*='name_type");
But this is right:
let sname = $("input[name*='name_type']");
Otherwise, it works just fine (well, certain optimizations can be done, that's true, but still it works as is) -- if I have guessed your HTML structure correctly, see example below. (Disclaimer: this is by no means a good piece of code with best pracrices etc. This is just a reproduction of original task with minimal fix to make it work.)
$(document).ready(e => {
$(".btnedit").click(e => {
textvalues = displayData(e);
let sname = $("input[name*='name_type']");
let sage = $("input[name*='age_type']");
let sgender = $("input[name*='gender_type']");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody">
<tr>
<td data-name="1">a1</td>
<td data-name="1">b1</td>
<td data-name="1">c1</td>
<td><button class="btnedit" data-name="1">edit</button></td>
</tr>
<tr>
<td data-name="2">a2</td>
<td data-name="2">b2</td>
<td data-name="2">c2</td>
<td><button class="btnedit" data-name="2">edit</button></td>
</tr>
</tbody>
</table>
Type: <input type="text" name="name_type" /><br />
Age: <input type="text" name="age_type" /><br />
Gender: <input type="text" name="gender_type" />
Possible reason of could be this: data-name is invalid everywhere in your table. If that's not the case, please share some more code. Minimal yet complete example would be great.
Update: in your example HTML I see no data-name attributes at all, and clickable element also does not have it. So, your selector $('#tbody th td') matches all TDs, and that's why you see whole table in output.
So, look at the example above and do the same with data-name: every <td> and the button on one row have the same value in that attribute.

HTML form doesn't capture all the checkboxes from Bootstrap responsive table

I have a table which displays results from my DB. In the last column I have checkboxes and by clicking submit button I am sending an array of account_id's to another php file. Everything works fine but the problem is that I am using a Bootstrap responsive table which can show 10-100 results on each page and the form only captures results on the current page. If I check boxes on different pages and switch between them, they still remain checked, though.
Here is my HTML:
<form action="compare.php" method="post">
<table class="table table-hover" id="dataTables-example">
<thead>
<tr>
<th style="text-align:center;">Account name</th>
<th style="text-align:center;">Address</th>
<th style="text-align:center;">Phone number</th>
<th style="text-align:center;">Website</th>
<th style="text-align:center;">Compare</th>
</tr>
</thead>
<tbody>
<?php
$result= mysql_query("select * from accounts order by account_name ASC" ) or die (mysql_error());
while ($row= mysql_fetch_array ($result) ){
?>
<tr>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['account_name'];?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['address']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['phone_number']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['website']; ?></td>
<td> <input type="checkbox" name="checkboxvar[]" value="<?php echo $row ['account_id'];?>" /></td>
</tr>
<?php } ?>
</tbody>
</table>
<input class="btn btn-success" type="submit" value="Compare" id="submit">
</form>
I tried to use jQuery to see if it can capture the checkboxes from the whole table, but results is the same as trying an HTML form.
This script is supposed to capture them and make an alert:
<button id="bt1">Get</button>
<script>
$('#bt1').on('click', function () {
//Get checked checkboxes
var checkedCheckboxes = $("#dataTables-example :checkbox:checked"),
arr = [];
//For each checkbox
for (var i = 0; i < checkedCheckboxes.length; i++) {
//Get checkbox
var checkbox = $(checkedCheckboxes[i]);
//Get checkbox value
var checkboxValue = checkbox.val();
//Get siblings
var siblings = checkbox.parent().siblings();
//Get values of siblings
var value1 = $(siblings[0]).text();
var value2 = $(siblings[1]).text();
arr.push(checkboxValue + '-' + value1 + '/' + value2);
alert(checkboxValue + '-' + value1 + '/' + value2);
}
});
</script>
Is there a way to do it?
You can use Datatables object:
$('input', oTable.fnGetNodes()).each(function () {
if($(this).is('checked')){
console.log($(this).val());
}
});
Solved!
Include this script:
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/f2c75b7247b/api/fnGetHiddenNodes.js"></script>
And this paste this function:
<script>
$(document).ready(function() {
oTable = $('#yourTableID').dataTable();
$('form').submit(function(){
$(oTable.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
});
</script>
All checkboxes are captured by clicking submit button.

Submit Multiple, dynamically created forms but not all

So here we go. I have a page that lists a bunch of unscored sports games. Here is the query I run to generate the page.
<div id="NFL">
<?php
foreach ($conn->query("SELECT * FROM game_data WHERE sport='NFL' AND awayscore IS NULL ORDER BY date DESC") as $NFL) {
echo '<form method="post" action="update_score.php">
<table class="table table-bordered">
';
echo '
<thead>
<tr>
<th width="5%" class="head0">Rotation</th>
<th width="45%" class="head1">Team</th>
<th width="10%" class="head0">Money Line</th>
<th width="10%" class="head1">Spread</th>
<th width="10%" class="head0">Over/Under</th>
<th width="10%" class="head1">Score</th>
</tr>
</thead>';
echo '
<tr>
<td colspan="6">
';
$date = date_create($NFL['date']);
echo date_format($date, 'l F jS Y \# g:iA');
echo '
</td>
</tr>';
echo '
<tr>
<td>'.$NFL['awayrotation'].'</td>
<td>'.$NFL['awayteam'].'</td>
<td>'.$NFL['awaymoneyline'].'</td>';
echo '
<td>
';
if ($NFL['awaymoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['awaymoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '
</td>';
echo '
<td>'.$NFL['total'].'</td>
<td><input type="text" required name="awayscore"></input></td>
</tr>';
echo '
<tr>
<td>'.$NFL['homerotation'].'</td>
<td>'.$NFL['hometeam'].'</td>
<td>'.$NFL['homemoneyline'].'</td>';
echo '
<td>
';
if ($NFL['homemoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['homemoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '
</td>';
echo '
<td>'.$NFL['total'].'</td>
<td><input type="text" required name="homescore"></input></td>
</tr>';
echo '
<tr><td colspan="6" align="right"><input type="hidden" name="id" value="'.$NFL['id'].'"><span style="padding-right:15px"><input type="submit" value="Submit Score"></span></td></tr>
</table>
</form>';
}
?>
</div>
This is what I'm looking to do, I would like to have a button to submit multiple forms. Only though if they have placed a value in the score. Is this possible? I have read about doing multiple forms based off names but these forms are being created dynamically. I look forward to your insight.
here try this
I placed a counter that increments by one per SQL result processed This will also be a key we will use later
The counter is now added to the end of the name fields of the inputs (in front of a "-" to be exploded later)
At the bottom of the script is a little code how I would handle the back end information
<?php
$count = "0";
echo '<form method="post" action="update_score.php"><table class="table table-bordered">';
foreach ($conn->query("SELECT * FROM game_data WHERE sport='NFL' AND awayscore IS NULL ORDER BY date DESC") as $NFL) {
$count = $count+1;
echo '<thead>
<tr>
<th width="5%" class="head0">Rotation</th>
<th width="45%" class="head1">Team</th>
<th width="10%" class="head0">Money Line</th>
<th width="10%" class="head1">Spread</th>
<th width="10%" class="head0">Over/Under</th>
<th width="10%" class="head1">Score</th>
</tr></thead>';
echo '<tr><td colspan="6">';
$date = date_create($NFL['date']);
echo date_format($date, 'l F jS Y \# g:iA');
echo '</td></tr>';
echo '<tr><td>'.$NFL['awayrotation'].'</td><td>'.$NFL['awayteam'].'</td><td>'.$NFL['awaymoneyline'].'</td>';
echo '<td>';
if ($NFL['awaymoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['awaymoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '</td>';
echo '<td>'.$NFL['total'].'</td><td><input type="text" required name="awayscore-$count"></input></td></tr>';
echo '<tr><td>'.$NFL['homerotation'].'</td><td>'.$NFL['hometeam'].'</td><td>'.$NFL['homemoneyline'].'</td>';
echo '<td>';
if ($NFL['homemoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['homemoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '</td>';
echo '<td>'.$NFL['total'].'</td><td><input type="text" required name="homescore-$count"></input></td></tr>';
echo '<tr><td colspan="6" align="right"><input type="hidden" name="id-$count" value="'.$NFL['id'].'"><span style="padding-right:15px">';
}
echo '<input type="hidden" name="count" value="$count">'
echo '<input type="submit" value="Submit Score"></span></td></tr></table></form>'
// back end
$counter = 0;
while ($counter++ < $_POST['count'])
{
$name = $_POST["name-$counter"];
$awayscore = $_POST["awayscore-$counter"];
$homescore = $_POST["homescore-$counter"];
$id = $_POST["id-$counter"]; // considering you may need to get rid of the count
$name = explode("-", $name);
$name = $name[0];
// ect ect
// enter in to data base
//clear all data in strings
}
?>
Sorry about that this was due to haters :|
more to the point yes the back end code is for your passer (the code the form is pointed at)
NB: your PHP style is older than what most use now, close to what I use - just check that all tutorials you use give you references to PHP 5.3 and when in doubt go to php.net and check the function calls for version use - syntax and alternate options

Exclude Specific Columns when exporting data from HTML table to excel

I am using this script for exporting data from HTML table to Excel.
<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
I found this here
but when i export this data it includes all columns in HTML table as expected to do. but my last row contains some icons that i don't want to export to excel.
<div class="row" style="margin-left:20px;">
<div class="grid_4">
<div class="da-panel collapsible">
<input type="button" class="btn btn-success" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel" style="float:right">
<div class="da-panel-content">
<div class="da-panel-title" style="border-top:1px solid #ccc;border-bottom:1px solid #ccc">
<h3 style="padding-left:10px;font-weight:bold;">Staff Training Information</h3></div>
<table class="da-table da-ex-datatable-numberpaging" id="testTable" width="100%">
<thead width="100%">
<tr>
<th width="10%">Staff ID</th>
<th width="10%">Name</th>
<th width="10%">Location</th>
<th width="10%">POCT Test</th>
<th width="10%">Initial Training Date</th>
<th width="10%">Annual Competency Date</th>
<th width="10%">Competency Type</th>
<th width="1%">Next Competency Date</th>
<th width="39%">Action</th>
</tr>
</thead>
<tbody width="100%">
<?php
include_once('database.php');
$pdo = Database::connect();
$sql = 'SELECT * FROM competency';
foreach ($pdo->query($sql) as $row) {
$id = $row['staff_id'];
echo '<tr>';
echo '<td width="10%">'. $row['staff_id'] . '</td>';
$sql1 = "SELECT *FROM staff WHERE StaffID='$id'";
foreach($pdo->query($sql1) as $res)
{
echo '<td width="10%">'. $res['StaffName'] . '</td>';
}
echo '<td width="10%">'. $row['location'] . '</td>';
?>
<td width="10%">
<?php
$s = $row['poct_test'];
$val = explode(" ",$s);
for ($i=0; $i<sizeof($val); $i++)
{
$v = $val[$i];
echo $v."<br/>";
}
?>
</td>
<?php
echo '<td width="10%">'. $row['date_of_initial_training'] . '</td>';
echo '<td width="10%">'. $row['annual_competency'] . '</td>';
echo '<td width="10%">'. $row['type_of_competency'] . '</td>';
echo '<td width="1%">'. $row['next_competency'] . '</td>';
echo '<td width="39%">';
echo '<img src="images/ic_zoom.png" height="16" width="16" />';
echo ' ';
echo '<img src="images/icn_edit.png"/>';
echo ' ';
?>
<img src="images/icn_logout.png"/>
<?php
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
As shown in code that last 3 echo contains update/delete icons. I just want to exclude Action column when exporting the table content in excel.
Any help would be highly appreciated.
You can use selectors from jQuery, clone of your table in memory then remove elements you don't want with appropriate selector.
var $table = $('#testTable').clone();
$table = filterNthColumn($table, 9); //remove Action column
function filterNthColumn($table, n){
return $table.find('td:nth-child('+n+'), th:nth-child('+n+')').remove();
}
make a hidden div under the table
<div class="exportData"> </div>
Then on click of the export button call export.php through ajax and put the result into exportData div. Then you can call your print script on the new data brought.
$.post( "export.php", function( data ) {
$( ".result" ).html( data );
});
Copy past your for loop on export.php and delete the two cols.
I think you can just clone the table firstly, remove the action column, and "tableToExcel" the cloned table.
To make the column removing easier, add class "action_th" to action th, and class "action_td" to action td.
Then it's like this,
var exTable = $('#testTable').clone();
//remove the action th/td
exTable.find('.action_th, .action_td').remove();
//then tableToExcel(exTable, ..
This works for me -
$('#divTableContainer').clone().find('table tr th:nth-child(7),table tr td:nth-child(7)).remove().end().prop('outerHTML')

How to grab the values from an HTML table's cells using JavaScript

I'm trying to grab the cell values from an HTML table so that I can save them into a MySQL table via a call to PHP. I'd like to use JavaScript rather than jQuery.
I'm giving each TR a distinct ID based on the MySQL table's ID field. Also, each TD input cell has a unique ID based on the MySQL table's ID field. Not sure if I need all those, but I used them.
How do I grab the cell's value so that I can pass it to a PHP procedure(I know how to code this PHP) to save the data into MySQL? My JavaScript code below grabs the "innerHTML" but I need to grab the cell value's instead.
For example, if I have 3 rows of data from a MySQL table, with fields id and amount, with values below, how do I grab the "3" and the "1.99"?:
id amount
-------------
1 100.00
2 9.99
3 1.99
Here is a sample of the PHP/HTML code for the table, submit button and onclick call:
(this is a very simplified version of my actual code but should convey the idea)
<?php
/* define mysql database connect, query and execute it returning result set into $result, id=integer primary key, is_active=tinyint(0 or 1), amount=decimal(12,2) */
/* ... */
/* output form/table */
echo "<form id='myform' name='myform' >" ;
echo "<table id='mytable' name='mytable'>" ;
while($row = mysql_fetch_array($result))
{
$id = $row['id'] ;
$amount = $row['amount'] ;
$tr_id = "tr_id_" . trim((string)$id) ;
$td_id = "td_id_" . trim((string)$id) ;
$td_amount_id = "td_amount_id_" . trim((string)$id) ;
$input_amount_id = "input_amount_id_" . trim((string)$id) ;
echo "<tr id='$tr_id' name='$tr_id'>";
echo "<td id='$td_id_account' > $id </td>" ;
echo "<td id='$td_amount_id' > <input type='text' id='$input_amount_id' value=$amount > $amount </td>" ;
echo "</tr>";
}
echo "</table>";
echo "</form>" ;
/* submit button and onclick call */
echo "<br />" ;
echo "<table>";
echo "<tr>" ;
echo "<td>";
echo "<button type='button' " . 'onclick="SubmitTableData(\'' . "mytable" .'\');"' . ">Submit</button>" ;
echo "</td>" ;
echo "</tr>";
echo "</table>";
?>
And here is a sample of my JavaScript function used to loop through the rows of the HTML table:
function SubmitTableData(TableID)
{
var table = document.getElementById(TableID);
for (var i = 0, row; row = table.rows[i]; i++)
{
// iterate through rows
for (var j = 0, col; col = row.cells[j]; j++)
{
// iterate through columns
alert(col.innerHTML);
}
/* call PHP procedure with row's cell values as parameters */
/* ... */
break;
}
}
Use the innerText property for the td. Here's a fiddle that shows how to use it.
HTML
<table>
<tr>
<td id="1">Bla</td>
<td id="2"><input id="txt" />Ble</td>
</tr>
</table>​
JavaScript
var td = document.getElementById('1');
alert(td.innerText);
var td2 = document.getElementById('2');
alert(td2.innerText);​
How to grab cell values from a table?
Update to address Elliots comment
See how to grab the cell value (innerText and data-value) in my new demo
In the table the attribute data-value is used to store some data (2B, 3C,..).
<table id="t2">
<thead>
<tr id="tr1"><th>Student Name<th>Course</tr>
</thead>
<tbody>
<tr id="tr2"><td data-value="2B">Bert2 <td>Economics </tr>
<tr id="tr3"><td data-value="3C">Clyde3 <td>Chemics </tr>
<tr id="tr4"><td data-value="4D"> <td>Digital Art</tr>
<tr id="tr5"><td data-value="5E">Ernest <td>Ecmoplasma </tr>
</tbody>
</table>
With jQuery and the right selector you can iterate over each cell:
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
// iterate over each row in table with id t2 in the table-body (tbody)
$('#t2 tbody tr').each(function(index){
// copy the text into an array
cellInnerText.push($(":first-child", $(this)).text());
//copy the data-value into an array
cellValue.push($(":first-child", $(this)).attr('data-value'));
});
// show content of both arrays
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
Alert the innerHTML of the first cell in the table's first row
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to alert the innerHTML of the first cell (td element with index 0) in the table's first row.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);
}
</script>
</body>
</html>
Place IDs on Your inputs with some pattern. for example <input type="text" id="input_0_0" name="whatever" /> where 0 is row and second 0 is column and then instead your alert type
v = document.getElementById('input_'+row+'_'+col).value;
It should help You get rolling now

Categories