Form action not working with table inside form - php

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

Related

Resized Page - Button submitting and not 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>

Query multiple SlideIn functions based on row number

I am looking for information on the best approach to creating a 'more details' section on a table generated by a MySQL query which is something like this:
<tr>
<th>First Name</th>
<th>Surname</td>
<th>Details</th>
</tr>
<tr>
<td>Joe</td>
<td>Blogs</td>
<td><a class="button-1" href="">More Details</td>
</tr>
<tr>
<th class="hidden_details hidden-1" colspan="3">...insert details...</th>
</tr>
Each row has a unique id e.g. button-2,3,4 etc that I can use to create a unique class for each details section and I can hide and show the details using JQuery:
$(document).ready(function() {
$('.button-1').click(function(){
var link = $(this);
$('.hidden-1').slideToggle('slow', function() {
if ($(this).is(':visible')) {
link.text('Hide Details');
} else {
link.text('More Details');
}
});
});
});
But my knowledge on JQuery is limited so the only way I could think to call the code would be to use php to create multiple versions. If anyone could point my in the direction of the best approach I would be grateful
check this code. it will help you. here id="view_1",id="show_1" 1 is your dynamic value from database .
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>First Name</th>
<th>Surname</td>
<th>Details</th>
</tr>
<tr>
<td>Joe</td>
<td>Blogs</td>
<td><a class="button-1" id="view_1" href="javascript:void(0)" onclick="show_details(1)">More Details</td>
</tr>
<tr>
<th class="hidden_details hidden-1" colspan="3" id="show_1">...insert details...</th>
</tr>
<tr>
<td>Joe1</td>
<td>Blogs2</td>
<td><a class="button-1" id="view_2" href="javascript:void(0)" onclick="show_details(2)">More Details</td>
</tr>
<tr>
<th class="hidden_details hidden-1" colspan="3" id="show_2">...insert details...</th>
</tr>
</table>
<script type="text/javascript">
function show_details(id) {
if ($('#show_'+id).is(':visible')) {
$('#view_'+id).text('More Details');
$('#show_'+id).hide();
} else {
$('#view_'+id).text('Hide Details');
$('#show_'+id).show();
}
}
</script>
<style type="text/css">
.hidden_details {
display: none;
}
</style>

jquery function not working on multiple rows

I have a table generated by jQuery, and a function that triggers an event when pressing ENTER.
The table generates correctly, but the function only works in the first wor of the table.
My html for the table is as follows:
<table border="1" id="PlantillaTable" name="PlantillaTable">
<tbody>
<tr>
<th rowspan="2" scope="col">Cargo</th>
<th colspan="12" scope="col">Escenario de Registro</th>
</tr>
<tr>
<td colspan="2">Folio</td>
<td colspan="2">Propietario</td>
<td >Grupo</td>
<td >Edad</td>
<td colspan="2">Folio</td>
<td colspan="2">Suplente</td>
<td >Grupo</td>
<td >Edad</td>
</tr>
<tr id="FilaTable">
<th scope="row" col="1" row="1">Cargo</th>
<td col="2" row="1">LISTA</td>
<td col="3" row="1">
<input type="text" id="AspiranteField" name="AspiranteField" placeholder="FOLIO" />
</td>
<td col="4" row="1">FOTO</td>
<td col="5" row="1">NOMBRE</td>
<td col="6" row="1">GRUPO</td>
<td col="7" row="1">EDAD</td>
<td col="8" row="1">LISTA</td>
<td col="9" row="1">
<input type="text" id="AspiranteField" name="AspiranteField" placeholder="FOLIO" />
</td>
<td col="10" row="1">FOTO</td>
<td col="11" row="1">NOMBRE</td>
<td col="12" row="1">GRUPO</td>
<td col="13" row="1">EDAD</td>
</tr>
</tbody>
And my function is as follows:
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
$('input').pressEnter(function(){
var trid = ($(this).closest('tr').attr('id'));
var opcion = ($(this).closest('td').index());
var valor = $(this).val();
$.getJSON("php/getAspiranteNombre.php?AspiranteId="+valor,function(data){
$.each(data,function(index,item) {
if(opcion < 4)
{
$("#"+trid+" td").eq(3).html('<p>'+item.NAME+'</p>');
$("#"+trid+" td").eq(4).html('<p>'+item.GRUPO+'</p>');
$.getJSON("php/getFoto.php?AspiranteId="+valor,function(data2){
$("#"+trid+" td").eq(2).html('<img src="aspiranteFoto/thumb_'+data2+'" width="50px" height="50px"/>');
});
$.getJSON("php/getEdad.php?Nacimiento="+item.EDAD,function(data3){
$("#"+trid+" td").eq(5).html('<p>'+data3+'</p>');
});
}
else
{
$("#"+trid+" td").eq(9).html('<p>'+item.NAME+'</p>');
$("#"+trid+" td").eq(10).html('<p>'+item.GRUPO+'</p>');
$.getJSON("php/getFoto.php?AspiranteId="+valor,function(data2){
$("#"+trid+" td").eq(8).html('<img src="aspiranteFoto/thumb_'+data2+'" width="50px" height="50px"/>');
});
$.getJSON("php/getEdad.php?Nacimiento="+item.EDAD,function(data3){
$("#"+trid+" td").eq(11).html('<p>'+data3+'</p>');
});
}
});
});
})
Which basically asks for a value in a database and places it in the spaces. The problem is that, in the first row of the table (dynamically generated) the function works perfectly, but in the subsequent rows it doesn't do anything.
Thanks in advance for your help!
You have to change the way to this one:
$("#PlantillaTable").find("input").keyup(function(ev) {
if (ev.which === 13 ) {
//yout code here...
}
});
Attaches to all input values inside this table the enter button handler.
http://jsfiddle.net/csdtesting/jkfL2v5s/
You first have to loop through each tr separately, then you can target the td's inside.
You can loop through the rows using $.each() like this:
$("table tr").each(function(i,v){
$(this).find("td:eq(3)").html('<p>'+item.NAME+'</p>');
....
});
and it will go through all your rows, not just the first one.

how to change all td numeric values into percentage values in jquery and PHP

I just want a function like when click toggle button the numeric values should be changed into percentage value by formula.
<table class="table table-striped table-bordered scrollable">
<thead>
<tr class="success">
<th>Answer</th>
<th>Total</th>
<th>PCP</th>
<th>OB/GYN</th>
<th>PAIN</th>
</tr>
</thead>
<tbody><tr><td class="left-align">Male</td>
<td>123</td>
<td>72</td>
<td>18</td>
<td>33</td>
</tr><tr><td class="left-align">Female</td>
<td>78</td>
<td>48</td>
<td>22</td>
<td>8</td>
</tr><tr><td class="left-align">All Respondent</td>
<td>201</td>
<td>120</td>
<td>40</td>
<td>41</td>
</tr></tbody>
</table>
my formula 201*value/100. can anybody tell the way how i can do this.with PHP and jquery.Any suggestion.
Try this
$('table tr td').each(function () {
var value = $(this).text();
if ($.isNumeric(value)) {
var final = 201 * value/ 100;
$(this).text(final)
}
});
DEMO
Yes it is possible using jQuery. You can do something like: (Sample)
<form method="POST">
<button type="button" id="toggle" data-state="off">Toggle</button>
<table class="table table-striped table-bordered scrollable" cellpadding="10">
<thead><tr class="success"><th>Answer</th><th>Total</th><th>PCP</th><th>OB/GYN</th><th>PAIN</th></tr></thead>
<tbody><tr><td class="left-align">Male</td><td>123</td><td>72</td><td>18</td><td>33</td></tr><tr><td class="left-align">Female</td><td>78</td><td>48</td><td>22</td><td>8</td></tr><tr><td class="left-align">All Respondent</td> <td>201</td> <td>120</td> <td>40</td> <td>41</td> </tr></tbody>
</table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var original = $('tbody').html();
$('#toggle').on('click', function(){
if($('#toggle').attr('data-state') == 'off') {
$('#toggle').attr('data-state', 'on').css({backgroundColor: 'green', color: 'white'});
$('td').each(function(index, element){
var current = $(this).text();
if($.isNumeric(current)) {
$(this).text(201*current/100);
}
});
} else {
$('#toggle').attr('data-state', 'off').css({backgroundColor: 'red', color: 'white'});
$('tbody').html(original);
}
});
});
</script>
This should toggle the original values and computed values
You can use .text(fn) to update the text of any element via a callback:
$('.table').find('td').text(function(_, value) {
return isNaN(+value) ? value : Math.round(201 * parseInt(value, 10) / 100) + '%';
});

Passing table data with post variables

Basically I have a table with a bunch of numbers coming from a database with columns for totals/subtotals. I do not intend to add any of the totals to the database, but I need to pass the total numbers from one page to the next. I can't seem to properly pass them as post variables using PHP... I'm wondering if this is a bad tactic firstly, secondly what should I do instead?
And if this is possible, how would I go about doing it? I haven't been able to derive the text between the < td >'s from using $_POST['tdname'].
Example code:
<form method="POST" action="newcivilreport2.php">
<div style="width:800px;text-align:left;margin:0 auto;padding-bottom:5px;">A. PENDING BALANCE</div>
<table border="1" style="width:800px;" ID="tableA">
<th style="width:40%;"></th>
<th style="width:15%;">Civil</th>
<th style="width:15%;">Asbestos</th>
<th style="width:15%;">Domestic</th>
<th style="width:15%;">Total</th>
<tr>
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil" name="PendingCivil">66</td>
<td id="PendingAsbestos">0</td>
<td id="PendingDomestic">0</td>
<td id="PendingTotal">0</td>
</tr>
</table>
<input type="submit" value="Save and Continue -->"></form></div>
newcivilreport2.php:
<?php
$_POST['PendingCivil'];
?>
POST will only send inputs like <input type='text|file|hidden|ect' />. Perhaps you would like to use AJAX. For example:
<table id="tData">
<tbody>
<tr>
<td class='dataVal1'>100</td>
...
$(document).ready(function() {
var toServer = {};
var data = $('#tData tbody tr td').each(function(key, value) {
toServer[$(this).attr('id')] = $(this).text();
});
$.ajax({
url: 'page.php',
data: toServer,
type: 'POST'
})
});
The <td> tag of a table does not provide values for a form.
Use a hidden field for your post:
http://www.w3schools.com/tags/att_input_type.asp
...
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil">66<input type="hidden" name="PendingCivil" value="66"></td>
...
Also, is it inside of a form?

Categories