PHP posting array values generated in JS for loop - javascript

I am using this script to generate a code which will later appear in a form.
I have this code working on 2 pages, but I have no idea why it is not able to post to te next page.
Below is my code:
function add(){
var coun = document.getElementById('count').value;
if(coun==""){var count = 1;}
else{var count = (coun*1)+1;}
if(count>=1){
show('cont_del');
}
var field = "";
var table = "";
var desc_arr = "";
var itn_arr = "";
var qty_arr = "";
var cls_arr = "";
var unp_arr = "";
var tot_arr = "";
for(var f=1;f<count;f++){
desc_arr = document.getElementById('desc'+f).value;
itn_arr = document.getElementById('itn'+f).value;
qty_arr = document.getElementById('qty'+f).value;
<? if($_POST['type']=="o"){ ?>
cls_arr = document.getElementById('cls'+f).value;
<? } ?>
unp_arr = document.getElementById('unp'+f).value;
tot_arr = document.getElementById('tot'+f).value;
field = field+"<table class='style5'><tr bgcolor='#FFFFFF'>";
field = field+"<td width='70'><b>"+f+"</b></td>\n";
<? if($_POST['type']!="s"){ ?>
field = field+"<td width='130'>";
field = field+"<input name='itn[]' id='itn"+f+"' type='text' class='input' size='5' maxlength='11' value='"+itn_arr+"'>";
field = field+"</td>\n";
<? } ?>
field = field+"<td width='200'>";
field = field+"<input name='desc[]' id='desc"+f+"' type='text'
class='input' size='30' value='"+desc_arr+"'>";
field = field+"</td>\n";
field = field+"<td width='70'>";
field = field+"<input name='qty[]' id='qty"+f+"'
onchange='totcalc("+f+");' type='text' class='input' size='3'
value='"+qty_arr+"'>";
field = field+"</td>\n";
<? if($_POST['type']=="o"){ ?>
field = field+"<td width='70'>";
field = field+"<input name='cls[]' id='cls"+f+"' type='text'
class='input' size='3' value='"+cls_arr+"'>";
field = field+"</td>\n";
<? } ?>
field = field+"<td width='150'>";
field = field+"<input name='unp[]' id='unp"+f+"'
onchange='totcalc("+f+");digit("+f+")' type='text' class='input'
size='10' value='"+unp_arr+"'>";
field = field+"</td>\n";
field = field+"<td width='150'>";
field = field+"<input name='tot[]' id='tot"+f+"' type='text'
class='input' size='10' value='"+tot_arr+"'>";
field = field+"</td>\n";
field = field+"</tr></table>\n\n";
}
var table = "<table class='style5'><tr bgcolor='#FFFFFF'>";
table = table+"<td width='70'><b>"+count+"</b></td>\n";
<? if($_POST['type']!="s"){ ?>
table = table+"<td width='130'>";
table = table+"<input name='itn[]' id='itn"+count+"' type='text'
class='input' size='5' maxlength='11'>";
table = table+"</td>\n";
<? } ?>
table = table+"<td width='200'>";
table = table+"<input name='desc[]' id='desc"+count+"' type='text'
class='input' size='30'>";
table = table+"</td>\n";
table = table+"<td width='70'>";
table = table+"<input name='qty[]' id='qty"+count+"'
onchange='totcalc("+count+");' type='text' class='input' size='3'
value='0'>";
table = table+"</td>\n";
<? if($_POST['type']=="o"){ ?>
table = table+"<td width='70'>";
table = table+"<input name='cls[]' id='cls"+count+"' type='text'
class='input' size='3'";
table = table+"</td>\n";
<? } ?>
table = table+"<td width='150'>";
table = table+"<input name='unp[]' id='unp"+count+"'
onchange='totcalc("+count+"); digit("+count+")' type='text'
class='input' size='10' value='0.00'>";
table = table+"</td>\n";
table = table+"<td width='150'>";
table = table+"<input name='tot[]' id='tot"+count+"'
type='text' class='input' size='10' value='0.00'>";
table = table+"</td>\n";
table = table+"</tr></table>\n\n";
document.getElementById("add").innerHTML = field + table;
document.getElementById("count").value = (count*1);
}
Later everything will be posted to the a div id='add' container in a nested table.
When I post the form there are no variables posted.

Related

Getting id from append table and use it in arithmetic javascript

I'm trying to get the id from append table and use it in arithmetic.
Here's the modal where i append the table and its in php
<tbody>
<tr class="item-row" id="item-row" onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' id='productUse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='productMsrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;' id='cost'><textarea rows='4' cols='10' name='Dealerphp' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td</td></tr>";
}
?>
</tbody>
here's the append javascript.
<script type="text/javascript">
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea class="productid" id="prc" value="'+ value +'</textarea></td><td class="item-name"><textarea class="productuse" id="productuse" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea class="description" id="description" value= "' + value2 +' </textarea></td><td class="item-name"><textarea class="msrp" id="msrp" value= "' + value3 + ' </textarea> </td><td class="item-name"><textarea class="cost" name="cost" id="'+ value4 + ' </textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty"></textarea></td><td class="item-name"><textarea id="price" class="price" name="price" disabled></textarea></td></tr>');
console.log(value4);
}));
});
});
</script>
and here's the arithmetic javascript to get the id, multiply to the column of qty and get the total.
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("₱" ,"") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
got it
function update_price() {
var row = $(this).parents('tr');
var a , w = 0;
var a = row.find('.cost').val().replace(/\,/g,'');
var w = row.find('.qty').val().replace(/\,/g,'');
var price = Number(a) * Number(w);
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}

Repeating jquery script in every row in table automatically

I have problem with this script. When I change value in column "TO" in table, script substract automatically in column "Number of hours" only in first row value but others no. I need application script with name "PRO1" (updateDue) in every row in table.
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<body onload="changeText()">
<?php
$date = date('Y-m-01');
$end = date('Y-m-t');
//, strtotime('-1 months')//
?>
<?php include 'dbconfig.php' ?>
<table border="1" id="myTable">
<tr>
<td>Date</td>
<td>From</td>
<td>To</td>
<td>Number of hours</td>
</tr>
<tr class="item">
<?php
date_default_timezone_set('UTC');
while(strtotime($date) <= strtotime($end)) {
$day_num = date('d', strtotime($date));
$day_name= date('l', strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
if (($day_name == "Saturday")||($day_name == "Sunday"))
{
echo "<td id='color'>$day_num $day_name</td><td></td><td></td><td></td></tr>";
}
else {
echo "<td>$day_num $day_name</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$starter= $query_row['start'];
echo "<input type='text' class='txtCal' id='num1' onchange='updateDue()' value=".$query_row['start'].">";
}
echo "</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$finisher= $query_row['end'];
echo "<input type='text' class='txtCal' id='num2' onchange='updateDue()' value=".$query_row['end'].">";
}
echo "</td><td>";
$ts1 = strtotime($starter);
$ts2 = strtotime($finisher);
$seconds_diff = $ts2 - $ts1;
$time = ($seconds_diff/3600);
echo "<input type='text' class='txtCal2' id='remainingval' value=".number_format((float)$time, 2, '.', '').">";
echo "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td></td>
<td>Sum:</td>
<td id="total_sum_value"><span id="total_sum_value"></span></td>
</tr>
</table>
<br>
<!-- SCRIPT NAME PRO1 -->
<script>
function updateDue() {
$('#myTable tr').each(function(){
var total = parseFloat(document.getElementById("num2").value);
var val2 = parseFloat(document.getElementById("num1").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
});
}
</script>
<script>
$(document).ready(function changeText(){
$(document).ready(function changeText(){
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
calculated_total_sum += parseFloat(get_textbox_value);
});
$("#total_sum_value").html(calculated_total_sum);
});
$("#myTable").on('change','input', '.txtCal2', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
</script>
I want dynamically change table. In column "FROM" and "TO" is value from database. This automatically subtract value (TO-FROM) and sum from this value is down. But when user change some value in column "FROM" or "TO", number will be count automatically. Thank you so much for every advice.
That's because you use the same ID for multiples TDs. You can't do that as an ID is supposed to be used once and help to identify a resource.
instead of an ID, you could use a class :
<table>
...
<tr>
<td><input type="text" class="txtCal num1" value="5" /></td>
<td><input type="text" class="txtCal num2" value="10" /></td>
<td><input type="text" class="txtCal2 remainingval" value="...">
</tr>
...
</table>
Then with jQuery, you can have access to your row values like this :
$('#myTable tr').each(function(){
var total = parseFloat($(this).find('.num2').val());
var val2 = parseFloat($(this).find('.num1').val());
...
var ansD = $(this).find(".remainingval");
ansD.val(total - val2);
});
Also let me point that mysql functions are deprecated and you should not use them anymore. Use PDO instead. (See Why shouldn't I use mysql_* functions in PHP?)

Transfer Table TD in textbox

This is the way on how I populate data in my table.
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var getval;
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
}
</script>
and this is my table where i put the data based on code above.
<table id = "TableContainer" cellspacing="2" cellpadding="3" width ="100%" align = "center" class="hoverTable">
<tr>
<th bgcolor = "darkgreen"><font color="white">#</font></th>
<th bgcolor = "darkgreen"><font color="white">Area</font></th>
<th bgcolor = "darkgreen" width = "200px"><font color="white">Customer Name</font></th>
<th bgcolor = "darkgreen"><font color="white">Person In Charge</font></th>
<th bgcolor = "darkgreen" width = "250px"><font color="white">Remarks</font></th>
<th bgcolor = "darkgreen"><font color="white">Status</font></th>
<th bgcolor = "darkgreen"><font color="white">Doc. Date</font></th>
<th bgcolor = "darkgreen"></th>
</tr>
<tr>
</tr>
</table>
Please bear with me. this code is perfectly running and im running the code by '<body onLoad = "GenerateTable()"> how ever as what you see on my code there is a code that looks like this.
<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
now it will create an image button for every row in my table and that code has a purpose and that is to transfer the data from td to textbox and other elements and here is my code for that.
<script>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
</script>
this is where the error starts when im clicking the image the row data is not transferring in my textbox whats the error?
Updated Code
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
</script>
TYSM
Could you put your second script $('.click-to-select').click(function(){...}) inside of GenerateTable() and after the for loop? Then check if the click handler is running by putting console.log('The dataid is:' + dataid) in here.
$('.click-to-select').click(function(){...
...
var documentdate = $(this).closest('tr').find('td.docdate').text();
console.log('The dataid is:' + dataid)
$('#dataid').val(dataid)
...
}
I can't tell for sure the order that your code executes because you have two separate script tags here, but it's possible your second script can't bind the click handler because the .click-to-selects haven't been created yet by GenerateTable().
Here is a working fiddle using nth-of-type selectors
First you need to remove the id from td because some of it matches with textbox element.
Then replace it with below line of code and do the same for each column.
var dataid = $(this).parent().siblings('.dataid').text();
I think , This function should be like below
Don't use the php tags because these are javascript variables .
function GenerateTable() {
var data = getData();
var table = document.getElementById("TableContainer");
for (var i = 12; i < data.length; i++) {
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ data[i][0] + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ data[i][1] +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + data[i][2] +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + data[i][3] +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + data[i][4] +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' + data[i][5] +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ data[i][6] +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
}
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
Hopefully , it may help you .

Are there any ways to get value of a table in a form but the table column was made with "document.getElementByID(id)"?

I'm just wondering if there are any ways to get the value of the document.getElementById(id) through forms using $_POST[] of php? Below is an example to which I'm trying to figure out how I could make it work. How the code below works is that when I click a table cell it will copy whatever the cell have and add it to my cart table and I would want to associate this cart table to a form where I could send it to my php script and get the data in the table but this cart table is produced by javascript just to be clear. Anyways here is the code below:
<?php
$sql = "SELECT * FROM userItems WHERE item_category = $choice" ;
$result = $db->query($sql);
$row = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $item):
echo '<tbody style="width:100%;height:100%;">';
echo '<tr>';
echo ' <td id="'.$item['item_name'].'" onclick="copyItem(id)" style="margin:-1px;width:261px;"> '.$item['item_name'] .'</td>';
echo '</tr>';
echo '</tbody>';
endforeach;
?>
<script>
function copyItem(id)
{
var table = document.getElementById("cart");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var value = document.getElementById(id).innerHTML;
var values = document.createElement("input").type="text".name="items[]".value=values;
// var sent = '<span><input type="text" name="items[]" value="" size="15" /></span>\r\n';
var dummy = '<span><input type="text" name="unitprice[]" size="30"/></span>\r\n';
var dummy1 = '<span><input type="number" name="qty[]" size="15"/></span>\r\n';
var dummy2 = '<span><input type="text" name="totalamount[]" size="15"/></span>\r\n';
var dummy3 = '<span><button class="btn btn-danger active" type="button" style="height:25px;width:68px;padding:2px;" onclick = "deleteRow(this)" >Delete </button></span>\r\n';
cell1.innerHTML = values;
cell2.innerHTML = dummy;
cell3.innerHTML = dummy1;
cell4.innerHTML = dummy2;
cell5.innerHTML = dummy3;
}
</script>
Any help would be great, Thanks!
If you write the php variable in the js function:
<?php
$sql = "SELECT * FROM userItems WHERE item_category = $choice" ;
$result = $db->query($sql);
$row = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $item):
echo '<tbody style="width:100%;height:100%;">';
echo '<tr>';
echo ' <td id="'.$item['item_name'].'" onclick="copyItem('.$item['item_name'].')" style="margin:-1px;width:261px;"> '.$item['item_name'] .'</td>';
echo '</tr>';
echo '</tbody>';
endforeach;
?>

ajax get checkbox name which is an array

updated
I'm using while loop to display checkbox, the value of the checkbox is the amount. The codes can now display the total value when a checkbox is checked through the ajax function. During form submit, how do i obtain the $ID of checked value? As the name of the checkbox is not an array, i have no idea how to do that other way. Please help :'( Thanks in advance!
PHP:
<table>
<form name="listForm">
<?php
while($row=mysql_fetch_assoc($result)){
$ID = $row['ID'];
$amount = $row['amount'];
?>
<tr>
<td><input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" value="<?php echo $amount;?>" onclick="calculate();"></td>
</tr>
<?php
}?>
</table>
</form>
javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}
You need to get the "data-payment-id" attribute from the checkboxes that are clicked as well. I'd store them in an array, then json stringify it to be sent in your form.
Javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
var idList = [];
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
idList.push(document.listForm.payID[i].getAttribute('data-payment-id'));
}
}
document.getElementById('sum').value = sum;
document.getElementById('count').value = count;
document.getElementById('idList').value = JSON.stringify(idList);
return true;
}
And then for your form, update it to have the hidden inputs and the onsubmit function - here's what I was using for a test:
HTML Form:
<form name="listForm" action="aoeu.php" method="post" onsubmit="calculate()">
<input type='checkbox' name="payID" value='1' data-payment-id='aaa'> 1<br>
<input type='checkbox' name="payID" value='2' data-payment-id='bbb'> 2<br>
<input type='checkbox' name="payID" value='3' data-payment-id='ccc'> 3<br>
<input type='hidden' id='sum' name='sum'>
<input type='hidden' id='count' name='count'>
<input type='hidden' id='idList' name='idList'>
<button type='submit'>Submit</button>
</form>
Then just make sure to json_decode() the idList you get in your PHP post.
I have updated now. In your php code amend this line:
<input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" id="payment_id[]" onClick="calculate()" value="<?php echo $amount;?>" >
And your Javascript function:
function calculate(){
var sum = 0;
var count = 0;
var a1=document.listForm['payment_id[]'];
for(i=0;i<a1.length;i++){
if (a1[i].checked){
sum += parseInt(a1[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}

Categories

Resources