How can I sort this foreach loop with jQuery? I will sort on id but I don't now how to do that.
<form id="fileForm" action="#" enctype="multipart/form-data" method="get">
<table cellpadding="2" cellspacing="0" width="100%" class="grid">
<tr>
<th>ID:</th>
<th>Time:</th>
<th>Location:</th>
<th>From IP:</th>
<th>Title (url):</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>12:00</td>
<td>Utrecht</td>
<td>192.019.192.00</td>
<td>site</td>
</tr>
</table>
</form>
http://datatables.net/ - is a client side JQuery plugin which will allow you to sort/paginate etc the final HTML that your PHP renders.
I would tend to use a server-side solution though if you have 1000s upon 1000s of rows as the time it takes to initially render the page would be very long.
<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th>Due</th>
<th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>John</td>
<td>jsmith#gmail.com</td>
<td>$50.00</td>
<td>http://www.jsmith.com</td>
</tr>
<tr>
<td>Bach</td>
<td>Frank</td>
<td>fbach#yahoo.com</td>
<td>$50.00</td>
<td>http://www.frank.com</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
});
</script>
You can also find more info abbout this plugin on jQuery TableShorter
here is another simple sort table using php code:
make a your-file.php, insert the below code, and upload to your folder. (this example is a very simple table for sorting and processing simple values, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
I really like this simple solution from Nick G at jQuery table sort
$('th').click(function(){
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() }
Related
I have a table inside a form like this:
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody">
<?php
if(!isset($_SESSION['products'])){
}else{
foreach($_SESSION['products'] as $product=>$details){
echo '
<tr class="txtMult">
<th scope = "row">'.$details["code_product"].'</th>
<th scope = "row">'.$details["name_product"].'</th>
<td><input class="val2" type="number" id="quantity" name="quantity" min="1" max="100"></td>
<td class="val1">'.$details["price"].'</td>
<td><span class="multTotal">0.00</span></td>
</tr>
';
};
}
?>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" value="Submit"/>
</div>
</form>
My actual problem is that submit botton isn't working, no actions are taken when I click button.
My idea is send all content of table to file.php through POST method.
There's a script that updates last with price*quantity but I don't think that problem lives there.
<script type="text/javascript">
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Anybody can help? :)
Once the small typo in the HTML is corrected and without your PHP logic ( no way to test that - hence hardcoded dummy data ) what you could do would be to use Javascript to send the form data rather than rely upon a regular form submission as was failing for you here. HTML content and text will not be sent via the form - only content from input elements so your form would submit a single field called quantity which is not what you want.
The following uses fetch to send the formData to your intended PHP script.
$(document).ready(function () {
function multInputs() {
var mult = 0;
$("tr.txtMult").each(function () {
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
return mult;
}
const submithandler=(e)=>{
// stop the regular `submit`
e.preventDefault();
// add form data to these variables
let fd=new FormData();
let payload=[];
// process the contents of the HTML table to populate the formData object
$("tr.txtMult").each(function(){
let item={
code:this.firstElementChild.textContent,
name:this.firstElementChild.nextElementSibling.textContent,
value:$('.val2', this).val()
};
// convert object to string
payload.push( JSON.stringify(item) );
});
fd.set('payload', payload );
// send the request
fetch( document.getElementById('myform').action,{ method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
alert( text )// do stuff with results?
})
.catch( err=>console.log('Error:%o',err) )
};
$(".txtMult input").keyup(multInputs);
$('[type="submit"]').click(submithandler);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<!-- Hardcoded example data -->
<tr class="txtMult">
<th scope = "row">Code ABC-1</th>
<th scope = "row">Name - 1</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">100</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-2</th>
<th scope = "row">Name - 2</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">200</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-3</th>
<th scope = "row">Name - 3</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">300</td>
<td><span class="multTotal">0.00</span></td>
</tr>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" />
</div>
</form>
It is possible to use tables inside forms but I think you're approach is wrong. you can put a table inside a form or vice versa, and it is often useful to do so. But you need to understand what you are doing.
Tables and forms can be nested either way. But if you put forms into tables, each form must be completely included into a single table cell (one TD element in practice). Thereby the forms are each completely independent.
So try putting the form inside the table cell which requires the input
I have a html code below (created using a plugin).
I need to change colspan="6" to colspan="4".
I tried jQuery below, but it doesn't work...
Would you please help me?
<table class="shop_table">
<thead>
<tr><th></tr></th>
</thead>
<tbody>
<tr><td class="aa"></td></tr>
<tr><td class="bb"></td></tr>
<tr><td class="cc" colspan="6"></td></tr>
<tbody>
</table>
$('.shop_table').find('td:last-child').contents().filter(function() {
return this.nodeType===3;
}).remove().end().end().find('colspan="6"').replaceWith($(('colspan="4"'));
Thank you.
With the selector [colspan="6"] you can get to each and set a new attribute:
$('.shop_table [colspan="6"]').each(function() {
this.setAttribute('colspan', '4');
});
console.log($('table').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="shop_table">
<thead>
<tr><th></th></tr>
</thead>
<tbody>
<tr class="aa"><td></td></tr>
<tr class="bb"><td></td></tr>
<tr class="cc" colspan="6"><td></td></tr>
<tbody>
</table>
Or, without jQuery:
for (const elm of document.querySelectorAll('.shop_table [colspan="6"]')) {
elm.setAttribute('colspan', '4');
}
console.log(document.querySelector('table').innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="shop_table">
<thead>
<tr><th></th></tr>
</thead>
<tbody>
<tr class="aa"><td></td></tr>
<tr class="bb"><td></td></tr>
<tr class="cc" colspan="6"><td></td></tr>
<tbody>
</table>
You can use prop() or attr() and both methods will loop through all of them
$('.shop_table td[colspan="6"]').prop('colSpan', 4)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="shop_table" border=1>
<thead>
<tr><th>111</th><th>111</th><th>111</th><th>111</th><th>111</th><th>111</th><th>111</th></tr>
</thead>
<tbody>
<tr><td class="aa">222</td></tr>
<tr><td class="bb">333</td></tr>
<tr><td class="cc" colspan="6">444</td></tr>
<tr><td class="aa">222</td></tr>
<tr><td class="bb">333</td></tr>
<tr><td class="cc" colspan="6">444</td></tr>
<tbody>
</table>
Hey a simple answer to your question is this:
$("table tr:last td[colspan=6]").attr('colspan',4);
I select the Table, then the last TR, and then the TD representing the one you want to be changed.
Then I add the attribute colspan 4.
This is a codepen showing it working: https://codepen.io/SweetChillyPhilly/pen/MWJbBPo
And here is the SO question where you can read more about how this solution became to be
Replacing Colspan = "2" with Colspan = "4" using Jquery
Update, seems it is also happening when i go onto the next page (fullscreen this time).
I'm hoping someone could possible help me as this has been driving me crazy. I have a table full off orders which each row has a button. This button when submitted will show an alert.
I am using data-tables (Responsive), and when the table is all on the screen, the button works as intended. However, when the screen is resized and the button goes within the + icon to expand the row. The button is not running the jquery and is submitting the page.
I have no idea how to fix this and was wondering if there is a workaround. Here is a sample of the code if it helps.
<table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<form id="<?php echo $order['OrderNumber']; ?>">
<input type="submit" value="Submit">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
At the bottom of the page:
<?php foreach ($orders as $order): ?>
<script>
$('#<?php echo $order['OrderNumber']; ?>').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<?php endforeach; ?>
Any help would be appreciated! I have no idea why it isn't working when the table is resized.
Use a delegated event handler instead :
$('#datatable-buttons').on('submit', '#<?php echo $order['OrderNumber'];?>', function() {
alert('Form submitted!');
return false;
});
Your event handler does not work because the form not exists in dom at the time of declaration.
But all those dedicated #id based event handlers is completely unnecessary. A single (delegated) handler is sufficient :
$('#datatable-buttons').on('submit', 'form', function () {
alert('Form ' + $(this).attr('id') + ' submitted!');
return false;
});
Hey mate you could try something like this for the alert
<table id="datatable-buttons" class="table table-striped table- bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<button type="button" class="btnPress" id="<?php echo $order['OrderNumber']; ?>">Submit</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Bottom
<script>
$('.btnPress').on('click', function () {
alert('Form submitted!');
alert(this.id);
});
</script>
My project is how to showing cell of table not in text, but in select option.
I have simple code:
<form method="post">
<textarea name="input"></textarea>
<button type="submit" name="button">button</button>
<table class="table table-bordered" id="tableAll">
<thead>
<tr>
<th class="col-md-1">name</th>
</tr>
</thead>
<tbody>
<tr>
<?php
if(isset($_POST['button']))
{
echo "<td>".$_POST["input"]."</td>";
}
?>
</tr>
</tbody>
</table>
</form>
<style>
td { white-space:pre }
</style>
I was input in textarea like this:
Andy
Alex
John
etc...
So, from input I want convert cell of table to select option in my page like this:
<table class="table table-bordered" id="tableAll">
<thead>
<tr>
<th class="col-md-1">name</th>
</tr>
</thead>
<tbody>
<tr>
<select>
<option>Andy</option>
<option>Alex</option>
<option>John</option>
<option>etc...</option>
</select>
</tr>
</tbody>
</table>
You can do it like below:-
<?php
if(isset($_POST["input"]))
{
$select_data = explode("\n",$_POST["input"]); // explode input data with new line
}
?>
<?php if(count($select_data) >0){?>
<select>
<?php
foreach($select_data as $select_dat){?>
<option value = "<?php echo $select_dat;?>"><?php echo $select_dat;?></option>
<?php }?>
</select>
<?php }?>
I dynamically generated a php page with a single text element form and a table of data. Each row of the table has a barcode as the name (). As I scan each barcode in the form, I'd like to change the row color using jquery.
Php page simplified:
<form id="checkinProcess" class="mainForm" method="post" action="">
<label>Barcode:</label>
<input type="text" class="required" name="barocde" id="processBarcode"/>
<input type="submit" value="submit" class="blueBtn" />
</form>
<table class="display" id="barcodeTable">
<thead>
<tr>
<th>Barcode</th>
<th>Amount</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr id="B12345" class="odd">
<td>B12345</td>
<td>20.3</td>
<td>External</td>
</tr>
<tr id="B23456" class="even">
<td>B23456</td>
<td>19.6</td>
<td>Internal</td>
</tr>
<tr id="B34567" class="odd">
<td>B34567</td>
<td>22.0</td>
<td>Internal</td>
</tr>
</tbody>
</table>
Table Css:
tr.odd { background-color: #F9F9F9; }
tr.even { background-color: white; }
tr.curChecked {background-color: #33CC33; }
jQuery attempt:
$('#checkinProcess').submit(function(e){
e.preventDefault();
$("tr.processBarcode").removeClass("odd" "even").addClass("curChecked");
});
How do I pass the barcode scanned in the form to my JQuery to identify which tr tag's class I want changed? Can I even do that?
Thanks
<script>tr.curChecked {background-color: #33CC33; } </script>
<form id="checkinProcess" class="mainForm" method="post" action="">
<label>Barcode:</label>
<input type="text" class="required" name="barocode" id="processBarcodes" />
<input type="submit" value="submit" class="blueBtn" id="submitBtn" />
</form>
<div class="table">
<table class="display" id="testTable">
<thead class="tableheader">
<tr><th>No</th><th>Name</th><th>Age</th><th>Salary</th></tr>
</thead>
<tbody id="testBody">
<tr id="B000506" ><td>1</td><td>Abe</td><td>28</td><td>$100K</td></tr>
<tr id="B000501" ><td>2</td><td>Jimmy</td><td>29</td><td>$90K</td></tr>
<tr id="B000506" ><td>3</td><td>Dude</td><td>18</td><td>$50K</td></tr>
<tr id="B000506" ><td>4</td><td>Boyee</td><td>28</td><td>$40K</td></tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$("#submitBtn").on("click", highlight);
function highlight(evt) {
evt.preventDefault();
var scanbc = $("#processBarcodes").val();
$("#" + scanbc).addClass("curChecked");
$("#processBarcodes").val('');
$("#processBarcodes").focus();
</script>
Worked.