I am adding rows dynamically with autofilled values from database. After adding it, it has to calculate total. Now it is calculating total only for 1st row. for 2nd row onwards it is not calculating anything. And also overall total is not happening.
Here is my code
html form
<table class="table table-bordered">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()" /></th>
<th>No</th>
<th>Item ID</th>
<th>Description</th>
<th>UOM</th>
<th>Price</th>
<th>Tax</th>
<th>Quantity</th>
<th>Discount</th>
<th>Amount</th>
</tr>
<tr>
<td><input type='checkbox' class='case' /></td>
<td><span id='snum'>1.</span></td>
<td><input type="text" class="form-control" id="productcode_1" name="productcode[]"></td>
<td><input type="text" class="form-control" id="description_1" name="description[]"></td>
<td><input type="text" class="form-control" id="uom_1" name="uom[]"></td>
<td><input type="text" class="form-control price" id="price_1" name="price[]"></td>
<td><input type="text" class="form-control tax" id="tax_1" name="tax[]"></td>
<td><input type="text" class="form-control quantity" id="quantity_1" name="quantity[]"></td>
<td><input type="text" class="form-control discount" id="discount_1" name="discount[]"></td>
<td><input type="text" class="form-control amount" id="amount_1" name="amount[]"></td>
<td><button type="button" class='btn btn-danger delete'>-</button></td>
<td><button type="button" class='btn btn-success addmore'>+ </button></td>
</tr>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th style="text-align:center;" class="total">0<b></b></th>
</tfoot>
</table>
javascript
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
check();
});
var i = $('table tr').length - 1;
$(".addmore").on('click', function() {
count = $('table tr').length - 1;
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + i + "'>" + count + ".</span></td>";
data += "<td><input class='form-control' type='text' id='productcode_" + i + "' name='productcode[]'/></td> <td><input class='form-control' type='text' id='description_" + i + "' name='description[]'/></td><td><input class='form-control' type='text' id='uom_" + i + "' name='uom[]'/></td><td><input class='form-control' type='text' id='price_" + i + "' name='price[]'/></td><td><input class='form-control' type='text' id='tax_" + i + "' name='tax[]'/></td><td><input class='form-control' type='text' id='quantity_" + i + "' name='quantity[]'/></td><td><input class='form-control' type='text' id='discount_" + i + "' name='discount[]'/></td><td><input class='form-control' type='text' id='amount_" + i + "' name='amount[]'/></td></tr>";
$('table').append(data);
row = i;
$('#productcode_' + i).autocomplete({
source: function(request, response) {
$.ajax({
url: 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'items_table',
row_num: row
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_
$('#description_' + id[1]).val(names[1]); $('#uom_' + id[1]).val(names[2]); $('#price_' + id[1]).val(names[3]); $('#tax' + id[1]).val(names[4]);
}
});
i++;
});
function select_all() {
$('input[class=case]:checkbox').each(function() {
if ($('input[class=check_all]:checkbox:checked').length == 0) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
$('body').delegate('.quantity,.price,.discount,.tax', 'keyup', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').valr price = tr.find('.price').val tax = tr.find('.tax').val
var dis = tr.find('.discount').valr amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt) * (tax / 100);
tr.find('.amount').val(tax1al();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = $(this).val() - 0;
t += tax1;
});
$('.total').html(t);
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
$('#' + id).html(key + 1);
});
}
$('#productcode_1').autocomplete({
source: function(request, response) {
$.ajax({
url: 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'items_table',
row_num: 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#description_1').val(names[1]);
$('#uom_1').val(names[2]);
$('#price_1').val(names[3]);
$('#tax_1').val(names[4]);
}
});
ajax.php
<?php
require_once '../connect.php';
if($_POST['type'] == 'items_table'){
$row_num = $_POST['row_num'];
$name = $_POST['name_startsWith'];
$query = "SELECT items.iid, items.description, items.uom, items.selling_price, items.tax_id, taxes.tax_id, taxes.name, taxes.rate FROM items INNER JOIN taxes ON items.tax_id=taxes.tax_id where items.iid LIKE '".strtoupper($name)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['iid'].'|'.$row['description'].'|'.$row['uom'].'|'.$row['selling_price'].'|'.$row['rate'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
?>
Only 1st row total is getting calculated. Not getting what is wrong
I got it resolved.Because of the class i have used
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var tax = tr.find('.tax').val();
var dis = tr.find('.discount').val();
var amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt * (tax / 100));
//alert(tax1);
tr.find('.tamount').val(tax1);
ttotal();
tr.find('.amount').val(amt);
total();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = $(this).val() - 0;
t += amt;
});
$('.total').html(t);
}
function ttotal() {
var tt = 0;
$('.tamount').each(function(i, e) {
var tax = $(this).val() - 0;
tt += tax;
});
$('.ttotal').html(tt);
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
$('#' + id).html(key + 1);
});
}
Related
this code works but you need to select or click the data first before displaying the data. What i want to do is to use mouse hover and data will display because there are similar data upon entering and displaying the data so i think i should use mouse hover so you can see the difference of the data. Your help is much appreciated
enter image description here
<tr class='tr_input'>
<td><textarea rows="3" type='text' name='sear[]' class='form-control sear' id='sear_1'></textarea></td>
<td><textarea rows="3" type='text' name='fee[]' class='form-control fee' id='fee_1' ></textarea></td>
<td><textarea rows="3" type='text' name='description[]' class='form-control description' id='description_1' ></textarea></td>
<td><textarea rows="3" type='text' name='office[]' class='form-control office' id='office_1' ></textarea></td>
<td><input rows="3" type='text' name='amount[]' class='form-control amount payment' id='amount_1' ></td>
<td><input rows="3" type="text" id='fpay0' name='quantity[]' class="form-control qty payment" autocomplete="off"/></td>
<td><input type="text" class="form-control numeric_value0 subtotals" name="subtotal[]" id='subtotal_1' autocomplete="off"/></td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.sear', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var fee = response[0]['fee'];
var description = response[0]['description'];
var office = response[0]['office'];
var amount = response[0]['amount'];
var qty = response[0]['qty'];
var subtotal = response[0]['subtotal'];
document.getElementById('fee_'+index).value = fee;
document.getElementById('description_'+index).value = description;
document.getElementById('office_'+index).value = office;
document.getElementById('amount_'+index).value = amount;
}
}
});
return false;
}
});
});
// Add more
var index = 2;
$('#addmore').click(function(){
// Get last id
var lastarp_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastarp_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><textarea rows='3' type='text' name='sear[]' class='form-control sear' id='sear_"+index+"'></textarea></td><td><textarea rows='3' type='text' name='fee[]' class='form-control fee' id='fee_"+index+"' ></textarea></td><td><textarea rows='3' type='text' name='description[]' class='form-control description' id='description_"+index+"' ></textarea></td><td><textarea rows='3' type='text' class='form-control office' id='office_"+index+"' ></textarea></td><td><input rows='3' type='text' name='amount[]' class='form-control input-md amount paym' id='amount_"+index+"' ></td><td><input type='text' name='quantity[]' class='form-control qty paym' id='quantity_"+index+"' ></td><td><input type='text' class='form-control subtotals numeric_value' name='subtotal[]' id='subtotal_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
$('.paym').keyup(function() {
var ids = $(this).attr("id").split("_");
// alert(ids[1]);
var sum = 0;
var f = $('#amount_'+ids[1]).val();
var p = $('#quantity_'+ids[1]).val();
sum = Number(f) * Number(p);
$('#subtotal_'+ids[1]).val(sum.toFixed(2));
var sums = 0;
$('.subtotals').each(function() {
sums += Number($(this).val());
});
sums = sums;
$('#total').val(sums.toFixed(2));
$('#tes').val(combines($('#total').val()));
});
index=index+1;;
});
$( "#delete" ).click(function() {
var rowCount = $('#tab_logic tr').length;
var del = rowCount - 2;
var ind = del-1;
if(del==2){
}else{
$("#tab_logic tr:eq("+ind+")").remove();
del=del-1;
var sums = 0;
$('.subtotals').each(function() {
sums += Number($(this).val());
});
sums = sums;
$('#total').val(sums.toFixed(2));
$('#tes').val(combines($('#total').val()));
}
});
//end
//start
$('.numeric_value').keyup(function() {
var sum = 0;
$('.numeric_value').each(function() {
sum += Number($(this).val());
});
sums = sums;
$('#total').val(sum.toFixed(2));
$('#tes').val(combines($('#total').val()));
});
$('.payment').keyup(function() {
var sum = 0;
var f = $('#fpay0').val();
var p = $('#amount_1').val();
sum = Number(f) * Number(p);
$('.numeric_value0').val(sum.toFixed(2));
var sums = 0;
$('.subtotals').each(function() {
sums += Number($(this).val());
});
sums = sums;
$('#total').val(sums.toFixed(2));
$('#tes').val(combines($('#total').val()));
});
//endold
})
</script>
I can't comment(need 50 reputation), so I send a answer.
Try mouseover event, in replace click.
like there:
document.getElementById("some").addEventListener("mouseenter", function( event ) {
// todo something
}, false);
I create an dyamic form with Jquery, there will be the multiple select box and textbox, how can I group the data into one based on the user name. For example, there will be the multiple select box = lim, total = 20, how can I group this 2 into array as 1.
When click the save button the final data will be like below
array(
'lim' => 40,
'tan' => 10,
);
Code here: https://jsfiddle.net/7gbvfjdc/
You mean something like this ?
You save button event listener should have following code
$('.savebtn').on('click', function() {
var mapObj = {};
$('.listable .cb').each(function(index, item) {
var selectVal = $(this).find('select').val();
if (mapObj[selectVal]) {
mapObj[selectVal] += Number($(this).find('#amt1_' + index).val());
} else {
mapObj[selectVal] = Number($(this).find('#amt1_' + index).val());
}
});
console.log(mapObj);
});
var i = 0;
$('.addRow').on('click', function() {
addRow();
});
function addRow() {
var tr = '<tr class="cb" id="row_' + i + '"><td>';
tr += '<select class="form-control select2" id="name1_' + i + ' first" name="name[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function() {
var mapObj = {};
$('.listable .cb').each(function(index, item) {
var selectVal = $(this).find('select').val();
if (mapObj[selectVal]) {
mapObj[selectVal] += Number($(this).find('#amt1_' + index).val());
} else {
mapObj[selectVal] = Number($(this).find('#amt1_' + index).val());
}
});
console.log(mapObj);
});
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center">+</th>
</tr>
</thead>
<tbody class="text-center">
</tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
You can use reduce on the body trs to extract the data and sum it in the wanted object format. Like this:
const result = $('tbody tr').get().reduce((prev, ne) => {
const $this = $(ne);
const type = $this.find('select').val();
prev[type] += parseInt($this.find('input').val())
return prev;
}, {
lim: 0,
tan: 0
});
var i = 0;
$('.addRow').on('click', function() {
addRow();
/*
$('.select2').select2({
theme: 'bootstrap4',
ajax: {
url: '{{ route("getMember") }}',
dataType: 'json',
},
}); */
});
function addRow() {
i++;
var tr = '<tr id="row_' + i + '"><td>';
tr += '<select class="form-control select2" id="name1_' + i + ' first" name="name[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
/* tr += '<td><select class="form-control select2" id="name2_'+i+'" name="name2[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt2_'+i+'" class="form-control"></td>'; */
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('button').on('click', () => {
const result = $('tbody tr').get().reduce((prev, ne) => {
const $this = $(ne);
const type = $this.find('select').val();
prev[type] += parseInt($this.find('input').val())
return prev;
}, {
lim: 0,
tan: 0
});
console.log(result)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th>Second name</th>
<th>Second amount</th>
<th style="text-align:center">+</th>
</tr>
</thead>
<tbody class="text-center">
</tbody>
</table>
<button>
save
</button>
https://jsfiddle.net/moshfeu/20kczto7/14/
I'm working on an old project that wasn't developed by me at first. I need to make an Ajax request so that the values contained in the fields (more on that later) be sent to a php script which will then return their values into the correct td.
Here is the JavaScript/jQuery code.
$(function ()
{
$('form').on('submit', function (e)
{
e.preventDefault();
$.ajax
({
type: 'post',
url: 'envoi_dispo_semaine.php',
data: $('form').serialize(),
success: function ()
{
alert('Le planning a été mis à jour.');
}
});
});
jQuery(document).ready(function date()
{
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
var today = new Date();
var t = today.getWeek();
})
jQuery(document).ready(function()
{
jDispo = {};
jCharge = {};
jSolde = {};
var d = 0;
var c = 0;
var s = 0;
jQuery('.DISPO').each(function()
{
jDispo[d] = jQuery(this).val();
d++;
});
jQuery(".CHARGE").change(function()
{
var totalCharge = 0;
if(jQuery(".CHARGE").length > 0)
{
jQuery(".CHARGE").each(function()
{
jCharge[c] = jQuery(this).val();
c++;
totalCharge = totalCharge + jQuery(this).val();
});
}
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function()
{
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
});
});
$(document).ready(function()
{
if ($("#tab_projets table tbody tr:eq(2) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(5) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(8) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('font-color', 'black');
}
});
});
And here is check_charges.php:
<?php
include('connexion_db.php');
$charge = $_POST['charge'];
$dispo = $_POST['dispo'];
$solde = $_POST['solde']; //I'll need this one later on.
$res = $dispo - $charge;
echo $res;
?>
I also have some php code that allows me to generate a table (it's in the same file as the javascript):
<thead>
<?php
echo " <td colspan=2>Semaine n°</td>
<td>Retard</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
echo "<form action=\"envoi_dispo_semaine.php\" method=\"post\">
<td>
<input type=\"hidden\" name=\"semaine_id\" value=\"".$i."\" />".$i."</td>";
}
?>
</thead>
<tbody>
<?php
foreach($users as &$myUser)
{
echo " <tr class=".$myUser.">
<td width=66% rowspan=3><input type=\"hidden\" name=\"login\" value=\"".$myUser."\" onblur=\"updateCharge\"/>".$myUser."</td>
<td width=34%>Disponibilité</td>
<td rowspan=3></td>
";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query = requete_is_plancharges($req);
$row = mysql_fetch_row($query);
$affichageDispo = $row[0];
if ($affichageDispo == "")
{
$affichageDispo = 3;
}
echo "
<td>
<input class=\"DISPO\" type=\"number\" name=\"disponibilite[]\" value=".$affichageDispo." min=\"0\" max=\"5\" step=\"0.5\" class=\"input\"/>
</td>
";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Charge</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$reqTache = "
SELECT tache_id
FROM Tache
WHERE ebi_id = ".$ebi."
AND demande_id = ".$demande."
AND action_id = ".$action;
$resultatTache_id = requete_is_plancharges($reqTache);
$maTache = mysql_fetch_object($resultatTache_id);
$req_Charge = "
SELECT COUNT(charge) as charge_tache
FROM Charge_par_tache
WHERE tache_id =".$maTache->tache_id.
" AND semaine_id =".$i.
" AND login = '".$myUser."'";
$resultat_requete_Charge = mysql_fetch_object(requete_is_plancharges($req_Charge));
if ($resultat_requete_Charge->charge_tache > 0)
{
$req = "
SELECT Charge_par_tache.charge
FROM Charge_par_tache, Tache
WHERE Charge_par_tache.tache_id = Tache.tache_id
AND Tache.ebi_id = ".$ebi."
AND Tache.demande_id = ".$demande."
AND Tache.action_id = ".$action."
AND Charge_par_tache.login = '".$myUser."'
AND Charge_par_tache.semaine_id = ".$i;
$Charge = mysql_fetch_object(requete_is_plancharges($req));
} else
{
$Charge->charge = "";
}
echo " <input type = \"hidden\" name = \"tache_id\" value=".$maTache->tache_id.">
<td class=\"CHARGE\">";
$query = requete_is_plancharges($req);
$row = mysql_fetch_array($query);
$affichageCharge = $row[0];
echo " <input class=\"CHARGE\" type=\"number\" name=\"charge[]\" value=".$Charge->charge." min=\"0\" step=\"0.5\"/>
</td>";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Solde</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req1 = "
SELECT charge FROM Charge_par_tache WHERE login = '".$myUser."' AND semaine_id = ".$i;
$req2 = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query1 = requete_is_plancharges($req1);
$row1 = mysql_fetch_row($query1);
$query2 = requete_is_plancharges($req2);
$row2 = mysql_fetch_row($query2);
$solde=$row2[0]-$row1[0];
echo "<td class=\"SOLDE\"><input type=\"hidden\" class=\"SOLDE\" value=".$solde."/> ".$solde."</td>";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
<p><input type="submit" name="submit" value="Mise à jour"></p>
</form>
The problem is that I can't seem to retrieve $res. I'm just starting Ajax so I really don't know what to do, and couldn't find the answer on the Internet as I use a js array to store my values.
If I understand your problem you want to get the response value of "check_charges.php", that it is the $res value, isn't it? The value will be returned in the first parameter of success function of your ajax.
Your code:
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function(data)
{
// Store where you want the data value
alert('res value: ' + data);
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
I hope I have helped you.
Dynamically add or delete rows in a table using jQuery but how to keep data in arrays after removing a row and don't get the totalSum when I add new row after deleting previous one .row add sucessfully and get initial sum but aftre remove operation i get NAN total sum
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
</script>
<script>
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": $("#txt_price").val(),
"TXT_QUANTITY": $("#txt_quantity").val(),
"TOTAL_AMOUNT": $("#txt_price").val() * $("#txt_quantity").val()
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_"+itemCount+"'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_"+itemCount+"' value='" + arr['TXT_QUANTITY'] + "'></td><td id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = $(this).val();
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = $("#price_" + rowId).text();
if (value_quantity >= 0)
{
$("#" + rowId+"_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
var rows = array.length;
for (var i = 1; i <= rows; i++) {
total += parseInt($("#" + i + "_total").text());
//total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
}
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs()
{
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var iPrice = 0;
if ($("#txt_price").val() == "" || isNaN($("#txt_price").val())) {
iPrice = 0;
}
else {
iPrice = parseInt($("#txt_price").val(), 10);
}
var iQuatity = 0;
if ($("#txt_quantity").val() == "" || isNaN($("#txt_quantity").val())) {
iQuatity = 0;
}
else {
iQuatity = parseInt($("#txt_quantity").val(), 10);
}
szTotal = iPrice * iQuatity;
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": iPrice,
"TXT_QUANTITY": iQuatity,
"TOTAL_AMOUNT": szTotal
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_" + itemCount + "'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_" + itemCount + "' value='" + arr['TXT_QUANTITY'] + "'></td><td class='td_total' id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1 tbody").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = 0;
if ($(this).val() != "" && !isNaN($(this).val()))
{
value_quantity = parseInt($(this).val(),10)
}
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = 0;
if ($("#price_" + rowId).text() != "" && !isNaN($("#price_" + rowId).text())) {
value_price=parseInt($("#price_" + rowId).text(),10);
}
if (value_quantity >= 0) {
$("#" + rowId + "_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
//var rows = array.length;
//for (var i = 1; i <= rows; i++) {
// total += parseInt($("#" + i + "_total").text());
// //total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
//}
$('.td_total').each(function () {
if (!isNaN($.trim($(this).text())) && $.trim($(this).text()) != "")
{
total = total+parseInt($(this).text(),10)
}
});
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs() {
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tbody></tbody>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>
I successfully cloned my table rows, which has values retrieved from database. However I have few issues with it.I used class for all the elements as clone will duplicate IDs.No the problem raises because it unable to target each element uniquely. WHat's the way to do make each element / row unique here?
How the functions work:
When first select box selected, item for that selected id would appear in the next column.Followed by price textbox and quantity textbox. WHen both are filled up, last textbox for total amount would automatically appear.
Issues with the cloning are:
* WHen select box selected from the first/original row, all cloned items are updated with the value.Same goes for amount textbox and vise-versa.
My script:
<script>
var harga;
var qty;
$("input[name^=harga]").on("keyup", function () {
alert($(this).attr("id"));
console.log($(this).val());
harga = $(this).val();
});
$(".qty").on("keyup", function () {
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$(".amount").val(amount);
});
$(document).ready(function () {
$(".sub_item").hide();
$('.gr').change(function () {
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['
agency_id
'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".sub_item").show();
$(".it_id").empty();
for (i = 0; i < data.length; i++) {
$(".it_id").append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$(".it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$("#more_items").on("click", function () {
alert("Hi");
$(".clone_this").clone(true, true).insertBefore("#last_e");
});
$(function () {
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function () {
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide1").show();
} else {
$("#hide1").hide();
}
});
$('#insurance').change(function () {
$("#hide2").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide2").show();
} else {
$("#hide2").hide();
}
});
$('#bon').change(function () {
$("#hide3").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide3").show();
} else {
$("#hide3").hide();
}
});
});
</script>
Form
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr>
<th>Group Item</th>
<th>Nama Item</th>
<th>Harga</th>
<th>Kuantiti</th>
<th>Amount</th>
</tr>
<tr class="clone_this">
<td>
<select name='group' style="width:80px;" class="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach ($group as $k => $v) {
$i = 0;
$i++;
?>
<option value="<?php echo $v['group_id'] ?>"><?php echo $v['group_name'] ?></option>
<?php
}
?>
</select>
</td>
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
</select>
</td>
<td><input type="text" name="harga_<?php echo $i; ?>[]" id="<?php echo $i; ?>" value="" class="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty[]' class='qty'/>
</td>
<td><input type="text" name="amount[]" class="amount" value=""/></td>
</tr>
<tr id="last_e">
<td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
You need find the relative elements to update so
$(document).ready(function () {
$('#submit_item').on('keyup', '.qty, .harga', function () {
var $tr= $(this).closest('tr');
$tr.find('.amount').val($tr.find('.harga').val() * $tr.find('.qty').val() || 0)
})
$(".sub_item").hide();
$('#submit_item').on('change', '.gr', function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});
Demo: Fiddle