ajax result not showing properly in table - php

I need to refresh contents in table every 5 seconds. I did this with ajax and setInterval functions. But the result is not properly displayed.
This is the result displaying. Here the first row is replaced by last row. I couldn't find the reason.
Here is my code.
My controller
public function latestReport() {
$data['incomingCount'] = $this->Home_model->findCount('incoming');
$data['outgoingCount'] = $this->Home_model->findCount('outgoing');
$data['droppedCount'] = $this->Home_model->findCount('drop');
$data['latestReport'] = $this->Home_model->latestReport(10);
print_r(json_encode($data));
}
Script
function latestReport() {
$.ajax({
url : base_url + 'Home/latestReport',
type : 'POST',
success:function(data) {
var res = $.parseJSON(data);
$('#incomingCount').text(res.incomingCount);
$('#outgoingCount').text(res.outgoingCount);
$('#droppedCount').text(res.droppedCount);
var latestCount = res.latestReport.length;
for(var i = 0; i < latestCount; i++){
var count = parseInt(i) + 1;
$('#resNo').text(count);
$('#resSource').text(res.latestReport[i]['Source']);
$('#resDest').text(res.latestReport[i]['Destination']);
$('#resCallerID').text(res.latestReport[i]['CallerID']);
$('#CallerTime').text(res.latestReport[i]['CallStartTime']);
$('#resStatus').text(res.latestReport[i]['Status']);
$('#resAgent').text(res.latestReport[i]['Agent']);
$('#resType').text(res.latestReport[i]['Type']);
}
}
});
}
var myVar = setInterval(latestReport, 5000);
HTML
<table class="normal-table" id="senderidList">
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
<?php if( isset($latestReport) && !empty($latestReport)) {
$i = 1;
foreach($latestReport as $report) {
?>
<tr>
<td id="resNo"><?php echo $i++;?></td>
<td id="resSource"><?php echo $report['Source']?></td>
<td id="resDest"><?php echo $report['Destination']; ?></td>
<td id="resCallerID"><?php echo $report['CallerID']?></td>
<td id="CallerTime"><?php echo date('d-m-Y h:i:s A', strtotime($report['CallStartTime'])); ?></td>
<td id="resStatus"><?php echo $report['Status']?> </td>
<td id="resAgent"><?php echo $report['Agent']?> </td>
<td id="resType"><?php echo $report['Type']?> </td>
</tr>
<?php } }
else {?>
<tr><td colspan="4"> No details available</td></tr>
<?php } ?>
</table>
I am getting the result from controller properly. But something happened when showing in table.

This is because the cells in each row all have the same ID, so you are updating the first row 10 times.
HTML elements should not have duplicate IDs.
You can do this instead, in PHP:
<tr id="row-<?php echo $i; ?>">
<td class="resNo"><?php echo $i++;?></td>
...
Then in JavaScript:
$('#row-' + count + ' .resNo').text(count);
...
Also, there is no need for parseInt(i) - just use i.

You can display your data without giving ID's to 'td' tags in HTML
make your html as follow
<table class="normal-table" id="senderidList">
<thead>
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Write following code in Success of Your ajax function for appending row 1 by 1
$('#senderidList tbody').empty();//clear your data
var TableBody = '';
if (data.d.length > 0) {
//following $.each loop will Concate data one by one
$.each(data.d, function (i, latestReport) {
TableBody += '<tr><td>' + i + 1 + '<td><td>' + latestReport['Source'] + '<td><td>' + latestReport['Destination'] + '<td><td>' + latestReport['CallerID'] + '<td><td>' + latestReport['CallStartTime'] + '<td><td>' + latestReport['Status'] + '<td><td>' + latestReport['Agent'] + '<td><td>' + latestReport['Type'] + '<td></tr>';
});
}
else
{
TableBody = '<tr><td colspan="4"> No details available</td></tr>';
}
//append the created html to the table body using append function
$('#senderidList tbody').append(TableBody);
if You want to give Id to every 'td' then you can give in $.each
<td id="yourID'+i+'"> for every td in body tag

Related

Hiding table row based on incremental php variable attached to the row

How can I hide a particular <tr> based on php variable associated with that <tr>(incremental variable $i) with jQuery when the table is being populated dynamically through Mysql. I have looked around but not getting any clue.
<table id="example">
<thead>
<tr>
<th>S.No.</th>
<th>Item Number</th>
<th>Question</th>
<th>Option-A</th>
<th>Option-B</th>
<th>Option-C</th>
<th>Option-D</th>
<th style="text-align: center;">Correct Ans.</th>
<th style="text-align: center;">Marks</th>
<th style="text-align: center;">Action</th>
</tr>
</thead>
<tbody>
<?php
if ($query != '') {
$res = mysql_query($query) ;
$i = 1;
while($row = mysql_fetch_array($res))
{
extract($row);
?>
<tr class="record">
<td><?php echo $i ; ?></td>
<td><?php echo $item_no ; ?></td>
<td><?php echo $level_id ; ?></td>
<td><textarea disabled name="question" rows="4" cols="35"><?php echo $question ; ?></textarea></td>
<td><?php echo $option_A ; ?></td>
<td><?php echo $option_B ; ?></td>
<td><?php echo $option_C ; ?></td>
<td><?php echo $option_D ; ?></td>
<td><?php echo $correct_ans ; ?></td>
<td><?php echo $marks ; ?></td>
<td> </td>
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var $tr = $(this).closest('tr');
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
success : function(response) {
if(response=='deletion success'){
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
}
}
});
}
return false;
});
});
</script>
</tr>
<?php $i++; } }
</tbody>
</table>
And my ajax page,
<?php
header('Content-Type: application/json');
session_start();
require("../config.php");
require("../Database.class.php");
require("../site.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$fnc=new site_functions($db);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_ques","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_ques",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
if($db->query_update("tbl_ques", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
?>
You are already close - in fact it looks like your code should work on the first click at least. Anyway,
Change line
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
to
$('#' + del_id).closest('tr').remove(); });
What this does is find the delete button element in the DOM, then look 'up' the DOM structure to the first TR element, and remove that from the DOM.
It is generally better to rely on simple variables within async callbacks because relying on objects, such as $this or in your case $tr can cause issues where the object pointed to by the $tr variable is not the one you expected.
EDIT: Added the working snippet below to illustrate the technique. If you still have a problem please create a minimal verifiable version as a snippet from your code so that we can pinpoint the issue.
$('.del').on('click', function() {
$(this).closest('tr').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="example">
<thead>
<tr>
<th>First name</th>
<th>Second name</th>
<th>Age</th>
<th style="text-align: center;">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joe</td>
<td>Bloggs</td>
<td>22</td>
<td style="text-align: center;">
<button id='A1' class='del'>Delete</button>
</td>
</tr>
<tr>
<td>Jane</td>
<td>Bloggs</td>
<td>19</td>
<td style="text-align: center;">
<button id='A2' class='del'>Delete</button>
</td>
</tr>
<tr>
<td>Joanne</td>
<td>Bloggs</td>
<td>28</td>
<td style="text-align: center;">
<button id='A3' class='del'>Delete</button>
</td>
</tr>
</tbody>
</table>

fetch a row in php and apply datatable

Iam using DataTable this is my code:
var table = $('#open').DataTable( { });
This is my html table code:
<table id="open">
<thead>
<tr>
<th rowspan="2"> S.No </th>
<th rowspan="2"> Patient Name </th>
<th colspan="2"> Booking </th>
<th rowspan="2"> Insurance Company</th>
<th rowspan="2">Appointment Status</th>
<th rowspan="2">Edit</th>
</tr>
<tr>
<th> Date </th>
<th> Time </th>
</tr>
</thead>
<tbody id="booking">
</tbody>
</table>
This is my ajax code:
var date = $("#date").val();
$.ajax({
type: 'POST',
url: 'booked1.php',
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
alert(response);
$("#booking").html(response);
$("#loadarModal").modal('hide');
}
});
This my booked1.php code:
if (isset($_POST['date'])) {
$date = $_POST['date'];
$query = mysqli_query($conn, "select id as id, concat(fname,' ',lname) as name, date as date, bookingtoken as bookingtoken, inusrance as insurance,
appointment_status as appointment_status from at_booking where date='$date'
");
while ($rows = mysqli_fetch_assoc($query)) {
$name = $rows['name'];
$id = $rows['id'];
$date = $rows['date'];
$bookingtoken = $rows['bookingtoken'];
$insurance = $rows['insurance'];
$appointment = $rows['appointment_status'];
echo '<tr>';
echo "<td>$id</td>";
echo "<td>$name</td>";
echo "<td>$date</td>";
echo "<td>$bookingtoken</td>";
echo "<td>$insurance</td>";
echo "<td>$appointment</td>";
echo '</tr>';
}
}
Iam successfully fetching rows through php and appending response to tbody but data table is not working properly like search is not working and no of entries not working pagination is not displaying i dont knw how to solve this can anyone help me
If you will refer dataTables doc. Then you will find that the data from remote server must be in json format. While you are not sending data in json. That is the issue. You need to change your code as below
$result = array();
while ($rows = mysqli_fetch_assoc($query)) {
$name = $rows['name'];
$id = $rows['id'];
$date = $rows['date'];
$bookingtoken = $rows['bookingtoken'];
$insurance = $rows['insurance'];
$appointment = $rows['appointment_status'];
$result[] = array($name,$id,$date,$bookingtoken,$insurance,appointment);
}
}
echo json_encode(array("data"=>$result));
EDIT
Datatable itself giving you facility for ajax. No need to explicitly add ajax for it. Remove your ajax code and change your datatable initialization to below
$('#open').DataTable( {
"ajax": 'booked1.php'
});
Also you must have same number of th and td(number of columns must be same)
you can try this --- append table using json response :
<?php
if (isset($_POST['date'])) {
$date = $_POST['date'];
$query = mysqli_query($conn, "select id as id, concat(fname,' ',lname) as name, date as date, bookingtoken as bookingtoken, inusrance as insurance,
appointment_status as appointment_status from at_booking where date='$date'
");
$data = [];
$i=0;
while ($rows = mysqli_fetch_array($query)) {
$data[$i]['name'] = $rows['name'];
$data[$i]['id'] = $rows['id'];
$i++;
}
echo json_encode($data);
}
?>
<script>
var date = $("#date").val();
$("#open tbody > tr").remove();
$.ajax({
type: 'POST',
url: 'booked1.php',
dataType : "json",
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
$("#loadarModal").modal('hide');
table = '';
$.each(response,function(indx,obj){
table += '<tr>';
table += '<td>'+ obj.id +'</td>';
table += '<td>'+ obj.name +'</td>';
table += '</tr>';
});
$("tbody#booking").append(table);
}
});
</script>
var table = null;
$(document).ready(function() {
table = $('#example').DataTable();
AddRowsAfterFewSeconds();
});
function AddRowsAfterFewSeconds() {
setTimeout(function() {
var strTR = '<tr>' +
'<td>YYYYY Kelly</td>' +
'<td>Senior Javascript Developer</td>' +
'<td>TTTTTT</td>' +
'<td>22</td>' +
'<td>2012/03/29</td>' +
'<td>$433,060</td>' +
'</tr>' +
'<tr>' +
'<td>SSSSS Kelly</td>' +
'<td>Senior Javascript Developer</td>' +
'<td>BBBBB</td>' +
'<td>15</td>' +
'<td>2012/03/29</td>' +
'<td>$433,060</td>' +
'</tr>';
table.rows().remove();
$(strTR).each(function() {
table.row.add($(this));
});
table.draw();
}, 3000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Roomus</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
</tbody>
</table>
This method dynamically adds rows to the DataTable. (here simply i used the setTimeOut function instead the AJAX response). It will dynamically add rows after '3 seconds'
$(strTR).each(function() {
table.row.add($(this)).draw();
});
simply loops through all the rows after converting the plain html text to 'tr' elements, and then add to the table, and finally redraws the table after adding all rows.
I've seen option to add arrays directly to DataTable. But its not working in my code. So I added them in a loop.
$(document).ready(function () {
$('#booked').DataTable();
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="booked">
<thead>
<tr>
<th>Name</th>
<th>SurName</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>SurName</th>
</tr>
</tfoot>
<tbody>
<!-- Your Foreach loop starts here -->
<tr>
<td>Hello</td>
<td>How</td>
</tr>
<tr>
<td>Abc</td>
<td>XYZ</td>
</tr>
<!-- Your Foreach loop endshere -->
</tbody>
</table>

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.

Inserting each .post data into a <td> using .each

I was wondering if this is possible to be done with jQuery. Please see following code.
HTML
<table id="order">
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
</table>
javascript
$(document).ready(function(){
$("td.load_ads").each(function(){
$(this).html("Place a New Ad Free!");
});
var count=$("td.load_ads").length; //18
$.post('/fetch_orders.php',{count:count},function(data){
var data_arr=data.split('/end');
for(index=0;index < data_arr.length;index++){ //for each of the array values got back from fetch orders.php
.
..
... Stuck here. How to make each data_arr(ie: each data_arr[index]) go into each td?
.POST script
$count =$_POST['count'];
$query="SELECT * FROM orders1_manager_orders ORDER BY RAND() LIMIT $count";
$db->setQuery($query);
$ads=$db->loadRowList();
foreach($ads as $ads_to_display){
echo $orders_to_display[9].'/';
echo $orders_to_display[10].'/end';
}
As explained in the title, I need each order to go into each empty td slot in the above html table. But, if I were to put a .each() function after my .post, all of my tds will turn into the first data gotten from the script, meaning data_arr[1].
First, please have a look at:
http://php.net/manual/en/function.json-encode.php
http://www.islandsmooth.com/2010/04/send-and-receive-json-data-using-ajax-jquery-and-php/
Second: better use div insted tables, this would make you independent of client device screen size.
http://csswizardry.com/2011/08/building-better-grid-systems/
Third, this is absolutly horrible code but it should be your solution:
$("td.load_ads").each(function(){
$(this).html("Place a New Ad Free!");
});
var count=$("td.load_ads").length; //18
$.post('/fetch_orders.php',{count:count},function(data){
var data_arr = [];
var rows=data.split('/end');
for(index=0;index < rows.length;index++){
var row = rows[i].split('/');
for (var x in row) {
data_arr.push(row[x]);
}
}
var i = 0;
$("td.load_ads").each(function () {
if (data_arr[i]) {
$(this).html(data_arr[i]);
}
i++;
});
}
$query = Sql_Query("SELECT * FROM Table");
$num_rows = mysql_num_rows($query);
for($i=0; $i < $num_rows; $i=$i+5)
{
$query1 = Sql_Query("SELECT * FROM Table LIMIT ".$i.", 5 ");
print '<td valign="top">';
while ($row=mysql_fetch_assoc($query1))
{
print '<input type="checkbox" name="chk_group1[]" id="chk_group1" value="'.$row['isp_name'].'" /> '.$row['isp_name'].'<br />';
}
print '</td>';
}

jQuery with php while on table tr td sum of the column for sub total

i was wondering if my jquery is correct for add the td and get the total for the sub total and total.
my jquery is,
$(document).ready(function(){
var sum = 0;
var td = $('input[name=sumof]').val();
jQuery.each(td,function(number){
sum += parseInt($(this).val());
$('#total_f').val(sum);
});
})
and this is my html
<div class="quotation_computation" style="margin-top:50px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tr>
<th>#</th>
<th>Definition</th>
<th>Amount</th>
<th>Total</th>
<th>BTW</th>
</tr>
<?
$get_details = mysql_query( "SELECT * FROM jon_com_quo_computation WHERE com_code = '".$_GET['ccom']."' " ) or die ( mysql_error());
$found_record = mysql_num_rows( $get_details );
if ( $found_record != 0 ) {
while( $set_det = mysql_fetch_array( $get_details ) ) {
$total = $set_det['quo_quantity'] * $set_det['quo_amt'];
?>
<tr>
<td class="add_text">
<?=$set_det['quo_quantity'];?> x
</td>
<td class="add_text" width="250"><?=$set_det['quo_definition'];?></td>
<td class="sum_text">
<?=$set_det['quo_amt'];?>
<input type="hidden" name="sumof" value="<?=$set_det['quo_amt'];?>" />
</td>
<td class="add_text" id="total"><?=$total;?></td>
<td class="add_text"><?=$set_det['quo_btw'];?></td>
</tr>
<?
}
} else {
?>
<tr>
<td class="add_text">#</td>
<td class="add_text">Definition</td>
<td class="add_text">Amount</td>
<td class="add_text" id="total">Total</td>
<td class="add_text">BTW</td>
</tr>
<?
}
?>
</table>
</div>
<div class="sub_total_computation" style="width:200px; position:relative; left:325px;">
<?
$get_total_computation = SET_SQL( "SELECT quo_btw FROM jon_com_quo_computation WHERE com_code = '".$_GET['ccom']."' " );
?>
<table cellpadding="5" cellspacing="0" width="100%">
<tr>
<td><strong>Sub Total</strong></td>
<td>
<span id="total_f"></span>
<input type="hidden" name="total_f" value="" />
</td>
</tr>
<tr>
<td><?=$get_total_computation['quo_btw'];?></td>
<td><?=$btw;?></td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td><?=$btw;?></td>
</tr>
</table>
</div>
if you saw the hidden name=sumof im going to put there the answer also in the td class=sum_text but the answer did not appear.
Do we need to use on .keyup function so that the jquery will appear?
Or i just need to use the PHP so that it will work?
thank you sir.
Try this:
$(document).ready(function(){
var sum = 0;
$('input[name=sumof]').each(function(){
sum += parseInt($(this).val());
});
$('#total_f').val(sum);
});
Your variable td would only get one value out of the input elements, and NOT be sufficient to use as an object (the input element) to loop with your each() function. Also you only need to have the function output the sum once, so I took it out of the each loop.
To further make the function efficient You could use just the contents of the td element instead and completely remove the hidden input element:
$(document).ready(function(){
var sum = 0;
$('td.sum_text').each(function(){
sum += parseInt($(this).text());
});
$('#total_f').val(sum);
});
You have a problem here:
var td = $('input[name=sumof]').val(); // you are getting the value of the first matched element
jQuery.each(td,function(number){
sum += parseInt($(this).val());
You are assuming that td contains a collection, but when you use val(), the result is Description: Get the current value of the first element in the set of matched elements.
So just change it to:
var td = $('input[name=sumof]');

Categories