Jquery table math - php

I am looking for solution to below issue. I have dynamically created rows in table and they can have similar ids based on part number. I want some simple solution to doing simple math operations with numbers inside table. My table have one Q'ty field which is left for user to fill in, rest should be calculated automatically. Row math and column sums. I am beginner so this is what i came up with.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id*='kolicina_']").keyup(function(){
var a = $("[id*='cena_']").text();
var b = $("[id*='kolicina_']").val();
var c = a * b;
var d = c - b;
$("[id*='ukupno_']").html(c);
$("[id*='razlika_']").html(d);
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Price</td>
<td>Q'ty</td>
<td>TTL</td>
<td>Difference</td>
</tr>
<tr>
<td id="cena_1234567">2</td>
<td ><input type="text" id="kolicina_1234567"/></td>
<td id="ukupno_1234567"></td>
<td id="razlika_1234567"></td>
</tr>
<tr>
<td id="cena_223421">10</td>
<td ><input type="text" id="kolicina_223421"/></td>
<td id="ukupno_223421"></td>
<td id="razlika_223421"></td>
</tr>
<tr>
<td id="cena_556677">200</td>
<td ><input type="text" id="kolicina_556677"/></td>
<td id="ukupno_556677"></td>
<td id="razlika_556677"></td>
</tr>
<tr>
<td>TTL</td>
<td>TTL</td>
<td>TTL</td>
<td>TTL</td>
</tr>
</table>
</body>
</html>

Note : From your question i think that you want to update the td values only for a single row (means based on the value which you are entering in 2nd column you want to update the calculated values in 3rd and 4th row).
Please check below code
$(document).ready(function(){
$("[id*='kolicina_']").keyup(function(){
var currentRow = $(this).parent().parent();
var td_cena = currentRow.find('td')[0];
var a = $(td_cena).text();
var b = $(this).val();
var c = a * b;
var d = c - b;
var td_ukupno = currentRow.find('td')[2];
var td_razlika = currentRow.find('td')[3];
$(td_ukupno).html(c);
$(td_razlika).html(d);
});
});
Please check this Fiddle.

Here you need to use id starts with selector like $("[id^='kolicina_']") which means grab all the DOM elements whose id starts with kolicina_. Then we search the tr object from where the event got originated and refer to associated DOM elements like below:
$(document).ready(function() {
$("[id^='kolicina_']").keyup(function() {
var trObj = $(this).closest("tr");
var a = parseFloat($(trObj).find("[id^='cena_']").text());
var b = parseFloat($(this).val());
var c = a * b;
var d = c - b;
$(trObj).find("[id^='ukupno_']").html(c);
$(trObj).find("[id^='razlika_']").html(d);
});
});
td {
min-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td>Price</td>
<td>Q'ty</td>
<td>TTL</td>
<td>Difference</td>
</tr>
<tr>
<td id="cena_1234567">2</td>
<td>
<input type="text" id="kolicina_1234567" />
</td>
<td id="ukupno_1234567"></td>
<td id="razlika_1234567"></td>
</tr>
<tr>
<td id="cena_223421">10</td>
<td>
<input type="text" id="kolicina_223421" />
</td>
<td id="ukupno_223421"></td>
<td id="razlika_223421"></td>
</tr>
<tr>
<td id="cena_556677">200</td>
<td>
<input type="text" id="kolicina_556677" />
</td>
<td id="ukupno_556677"></td>
<td id="razlika_556677"></td>
</tr>
<tr>
<td>TTL</td>
<td>TTL</td>
<td>TTL</td>
<td>TTL</td>
</tr>
</table>

Change the js like this
$(document).ready(function(){
$("[id*='kolicina_']").keyup(function(){
var clickid = $(this).attr('id') ;
var main = $(this).attr('id').slice(9);
var a = $('#cena_'+main).text();
var b = $('#kolicina_'+main).val();
var c = a * b;
var d = c - b;
$('#ukupno_'+main).html(c);
$('#razlika_'+main).html(d);
});
});

Related

AJAX element selection Issue with table row

I am trying to ajax delete rows in a table. It is working, except for the fact that it deletes the ENTIRE table... There is a table within the table the code is as follows;
$(document).ready(function() {
$(".delete").bind('click', function(e){
e.preventDefault();
var parent = $(this).parents('tr');
var string = 'id='+ parent.attr('id').replace('record-','') ;
$.ajax({
type: 'POST',
url: 'ajax_delete.php',
data: string,
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function(data) {
if(data.status == 'success'){
parent.slideUp(300,function() {
parent.remove();
});
}else if(data.status == 'error'){
parent.animate({'backgroundColor':'#eeeeee'},300);
} else {
parent.animate({'backgroundColor':'#eeeeee'},300);
}
},
});
});
});
The table layout;
<table class="tab_var1">
<tr>
<td class="tab_var1_pad">
<div class="v_tables">
<table>
<tr>
<td>
Domain Name
</td>
<td>
Stats Overview
</td>
<td>
Remove from CRON
</td>
</tr>
<tr class="record" id="record-1">
<td >
<a href="http://www.challengept.com" target="_blank">challengept.com<a>
</td>
<td >
<table >
<tr>
<td>
Traffic (Month)
</td>
<td>
No. Keywords
</td>
<td>
No. PPC Ads
</td>
<td>
Visibility
</td>
</tr>
<tr>
<td>
1796
</td>
<td>
367
</td>
<td>
0
</td>
<td>
0.0236900
</td>
</tr>
<tr>
<td>
Data Source - UK
</td>
</tr>
</table>
</td>
<td >
Remove
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
If anyone can let me know how I can select a single TR within the ajax that would be a great help. The TR I wish to select is the tr with the class "record" which has an a href button in the last td. I am using select parents tr?
You can use closest for this:
var parent = $(this).closest('tr');
var string = 'id='+ parent.attr('id').replace('record-','') ;
I think you can do it with better way as following:
1. Assign data attr for id field
Remove
2. Get data id
var string = $(this).data('id');
.parents() returns all the parents of the element. You just need to select the immediate parent or closest ancestor tr. Use the following jquery method
var parent = $(this).closest('tr');
See links
https://www.w3schools.com/jquery/traversing_parents.asp
Jquery row selecting in a button onClick

how to access td without class or id in ganon

My table is Like:
<table class="tl">
<tbody>
<tr class="tlr">
<td>abcd</td>
<td class="tli"><img src="img src here" alt="English" class="icon"></td>
<td>I WANT THIS TEXT</td>
<td class="sn">12</td>
<td class="ln">44</td>
<td><div class="r0"></div></td>
</tr>
</tbody>
</table>
I am trying to access plaintext of 3rd <td> (<td>I WANT THIS TEXT</td>).
I am very confused that how to get this.
Please help me
var text = $('.tlr td:nth-child(3)').text();
alert(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tl">
<tbody>
<tr class="tlr">
<td>abcd</td>
<td class="tli"><img src="img src here" alt="English" class="icon"></td>
<td>I WANT THIS TEXT</td>
<td class="sn">12</td>
<td class="ln">44</td>
<td><div class="r0"></div></td>
</tr>
</tbody>
</table>
Following code for get all td datas from clicking any row.
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 2; i < 3; i++) {
data.push(cells[i].innerHTML);
}
}
};
Jeet, you need to use Jquery Selectors... Take a look at the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ready demo</title>
<style>
p {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$( document ).ready(function() {
alert($( "table tbody tr td:nth-child(3)" ).text());
});
</script>
</head>
<body>
<table class="tl">
<tbody>
<tr class="tlr">
<td>abcd</td>
<td class="tli"><img src="https://upload.wikimedia.org/wikipedia/commons/2/2f/Google_2015_logo.svg" alt="English" class="icon"></td>
<td>I WANT THIS TEXT</td>
<td class="sn">12</td>
<td class="ln">44</td>
<td><div class="r0"></div></td>
</tr>
</tbody>
</table>
</body>
</html>
Hope this helps...

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