I have 2 java script codes, one work as a search suggestion and second is for adding another form fields dynamically and this second script also calculate values given in input fields, but both scripts have this 'ADD MORE PRODUCT' feature. What i want is; i want to combine both 'ADD more" feature, because 1st script works on id="" tag to identify field to show search result but second script not do it.
Fetching details in first row is successful, but when i click ADD more button populated by second script, it does not work
//Script to fetch details based on search box :
$(document).ready(function() {
$(document).on('keydown', '.prname', function() {
var id = this.id;
var splitid1 = id.split('_');
var index1 = splitid1[1];
$('#' + id).autocomplete({
source: function(request, response) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 3
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$(this).val(ui.item.label); // display the selected text
var prid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {
prid: prid,
request: 4
},
dataType: 'json',
success: function(response) {
var len = response.length;
if (len > 0) {
var id = response[0]['id'];
var fprice = response[0]['fprice'];
var packing = response[0]['packing'];
var pweight = response[0]['pweight'];
document.getElementById('fprice_' + index1).value = fprice;
document.getElementById('packing_' + index1).value = packing;
document.getElementById('pweight_' + index1).value = pweight;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function() {
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='name' id='name_" + index + "' placeholder='Enter name'></td><td><input type='text' class='phone' id='phone_" + index + "' ></td><td><input type='text' class='address' id='address_" + index + "' ></td><td><input type='text' class='custid' id='custid_" + index + "' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
// Second script to do calculation :
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('keyup change', function() {
calc_total();
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.fprice').val();
var discount = $(this).find('.discount').val();
$(this).find('.total').val((qty * price) - discount);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table class="table table-bordered table-hover" style='border-collapse: collapse;' id="tab_logic">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center"> Product </th>
<th width="190px" class="text-center"> Price </th>
<th width="30px" class="text-center"> Price for </th>
<th width="100px" class="text-center"> Packing </th>
<th width="80px" class="text-center"> Qty </th>
<th width="100px" class="text-center"> Discount </th>
<th width="150px" class="text-center"> Total </th>
</tr>
</thead>
<tbody>
<tr class='tr_input' id='addr0'>
<td>1</td>
<td><input type="text" name='product[]' id="prname_1" class="prname form-control" /></td>
<td>
<input type="number" name='price[]' id='fprice_1' class="form-control fprice price" step="0.00" min="0" />
</td>
<td><input style="width:70px" type="text" class="pweight input-group-text" id="pweight_1"></td>
<td><input type="text" name='pack[]' class="form-control packing" id='packing_1' step="0" min="0" /></td>
<td><input type="text" name='qty[]' class="form-control qty" id="qty_1" step="0" min="0" /></td>
<td><input type="text" name='discount[]' class="form-control discount" id="discount_1" step="0.00" min="0" /></td>
<td><input type="number" name='total[]' class="form-control total" id="total_1" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
Related
I need to get all values per column dynamically and save it using JS or Jquery. I have a photo here so that you guys can visualize what I am trying to do. Please see the image.
Sad to say this is as far as I can go. I cant seems to get what I realy want to achieve. Just a beginner here.
$(function() {
$('#add_supplier').click(function() {
$('#supplier_table > thead > tr#first-header').append(
'<th colspan="2" class="supplier_name"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>'
);
$('#supplier_table > thead > tr#second-header').append(
'<th>Price</th>' +
'<th>Total</th>'
);
$('#supplier_table > tbody > tr').not('#totals,#tr-td-2').append(
'<td class="ignore"><input type="text" class="form-control price text-right" ></td>' +
'<td><input type="text" class="form-control total text-right" readonly></td>'
);
$('#supplier_table > tbody > #totals').not('#tr-td-2').append(
'<td class="ignore"><input class="form-control" disabled></td>' +
'<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>'
);
$('#supplier_table > tbody > #tr-td-2').append(
'<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>'
);
//
refresh_index();
//
});
$('#add_terms').click(function() {
var $tableBody = $('#supplier_table').find("tbody").not('#totals'),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trNew.find('input').val('');
$trLast.after($trNew);
refresh_index();
});
// $('#add_supplier').click();
$('#add_item').click(function() {
$('#supplier_table > tbody').not('#totals, #tr-td-2').append(
// $("#supplier_table tbody tr:last").clone()
'<tr class="tbody-tr">' +
'<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control price"></td>' +
'<td><input type="text" class="form-control total for_sum-1" readonly=""></td>' +
'</tr>'
);
//
refresh_index();
//
});
//
function refresh_index() {
$('.price').each(function(i) {
i++;
$(this).attr('id', 'price-' + i);
$(this).attr('data-num', i);
event_handler();
});
$('.total').each(function(i) {
i++;
$(this).attr('id', 'total-' + i);
});
$('.qty').each(function(i) {
i++;
$(this).attr('id', 'qty-' + i);
});
$('.grandtotal').each(function(i) {
i++;
$(this).attr('id', 'grandtotal-' + i);
});
$('.supplier_name').each(function(i) {
i++;
$(this).attr('id', 'supplier_name-' + i);
});
}
refresh_index();
//
//
function event_handler() {
$('.price').unbind('keyup').bind('keyup', function() {
var id = this.id;
var num = id.split('-');
var pos = $(this).closest('tr').index() + 1;
var qty = $('#qty-' + pos).val();
var price = $(this).val();
var total = parseFloat(qty) * parseFloat(price);
if (isNaN(total)) {
var total = 0;
}
$('#total-' + num[1]).text(total);
$('#total-' + num[1]).val(total);
var num_of_supplier_name = $('.supplier_name').length;
sum_of_total();
});
}
function sum_of_total() {
// var sum = 0;
// //iterate through each textboxes and add the values
// $(".total").each(function () {
// //add only if the value is number
// if (!isNaN($(this).val()) && $(this).val().length != 0) {
// sum += parseFloat(this.value);
// }
// });
// //.toFixed() method will roundoff the final sum to 2 decimal places
// $("#grandtotal-"+num).val(sum);
var totals = [];
$('#tb').find('tr').each(function() {
var $row = $(this);
$row.children('td').not('.ignore').each(function(index) {
totals[index] = totals[index] || 0;
totals[index] += parseInt($(this).text()) || 0;
});
})
$('#totals td').not('.ignore').each(function(index) {
// $(this).text(totals[index]);
var id = index + 1;
$('#grandtotal-' + id).val(totals[index]);
});
$("#tb").on("click", "tr", function() {
$(this).find("td").slice(0, 4).prop("contenteditable", true);
});
// var max = 0;
// $('.grandtotal').each(function()
// {
// $this = parseInt( $(this).val() );
// // console.log($this);
// if ($this > max) {
// max = $this;
// }
// // $('.grandtotal').val(max).css('background-color','yellow');
// // console.log('Lowest Offer : '+max);
// });
// console.log('Lowest Offer : '+max);
// var high = Math.min.apply(Math, $('.grandtotal').map(function(){
// return $(this).val()
// }))
// console.log('Lowest Offer : '+high);
var vals = $('.grandtotal').map(function() {
return parseInt($(this).val(), 10) ? parseInt($(this).val(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
console.log(min);
// tag any cell matching the min value
$('.grandtotal').filter(function() {
// return parseInt($(this).val(), 10) === min;
if (parseInt($(this).val(), 10) === min) {
$(this).css("background-color", "#dff0d8");
} else {
$(this).css("background-color", "transparent");
}
});
}
//
});
<button type="button" class="btn btn-success" id="add_supplier">Add Supplier</button>
<!-- <button type="button" class="btn btn-default" id="add_item">Add Item</button> -->
<button type="button" class="btn btn-primary" id="add_terms">Add Terms</button>
<table class="table table-bordered" id="supplier_table">
<thead>
<tr id="first-header">
<th></th>
<th></th>
<th colspan="2" class="supplier_name" id="supplier_name-1"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>
</tr>
<tr id="second-header">
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="tb">
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Mouse" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="10" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Keyboard" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="20" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr id="totals">
<td class="ignore"></td>
<td class="ignore"></td>
<td class="ignore"><input class="form-control" disabled value="Grand Total : " style="text-align: right;"></td>
<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>
</tr>
<tr id="tr-td-2">
<td>
<p style="width: 60px;"></p>
</td>
<td><input style="font-weight: bold; text-align: right;" type="text" class="form-control" placeholder="Enter terms"></td>
<!-- <td ><p style="width: 60px;"></p></td> -->
<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>
</tr>
</tbody>
</table>
Actual Demo Link
JSFIDDLE
I'm having an issue using jQuery function multiplication (math) with dynamically created inputs (again created with jQuery). I can't get my function to bind to the new inputs. for the first row its work, but for second row it did not work (second row and more using dynamically input).
Here my html code
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem(); return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
And this my script
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
jumlah_input.setAttribute('autocomplete', 'off');
jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
function sum() {
var hrg = document.getElementById('hargaid').value;
var jml = document.getElementById('jumlahid').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('totalid').value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
Any help is appreciated.
You are not passing current id's of inputs to your sum method. and one more thing add jquery onkeyup event to your dynamic inputs. please refer below code -
$(function() {
$('#sample').on('click',additem)
$( "#nama" ).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode').val(ui.item.kode);
$('#harga').val(ui.item.harga);
}
});
});
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
var i = 1;
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
//harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
//jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
// harga_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
// jumlah_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="sample" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
Here is the sample, try this
$(function() {
$(document).on('click', '.btn-remove', function() {
// remove closest row on click of remove button
$(this).closest('tr').remove();
});
$(document).on('input', 'input.harga,input.jumlah', function() {
var hrg = $(this).closest("tr").find('input.harga').val();
var jml = $(this).closest("tr").find('input.jumlah').val();
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
$(this).closest("tr").find('input.total').val(result);
}
})
});
function additem() {
var rowHtml = '<tr>' +
'<td><input name="nama_input[]" class="nama form-control" /></td>' +
'<td><input readonly name="kode_input[]" class="kode form-control" /></td>' +
'<td><input name="harga_input[]" class="harga form-control" /></td>' +
'<td><input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" /></td>' +
'<td><input name="total_input[]" class="total form-control" /></td>' +
'<td><button class="btn btn-small btn-default btn-remove"><b>Hapus</b></button></td>' +
'</tr>';
$('#itemlist').append(rowHtml);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist'>
<tr>
<td>
<input name="nama_input[]" class="nama form-control" />
</td>
<td>
<input readonly name="kode_input[]" class="kode form-control" />
</td>
<td>
<input name="harga_input[]" class="harga form-control" />
</td>
<td>
<input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" />
</td>
<td>
<input name="total_input[]" class="total form-control" />
</td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem();
return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
I hope It will help
I am trying to dynamically add rows to a table to take orders and have created a javascript function for it.
function addnewrow()
{
var lastid = $("#table tr:last").attr("id");
var newid=lastid+1;
var newcolumn = document.createElement("tr");
newcolumn.id=newid;
newcolumn.innerHTML = "<td id='no"+newid+"'><a class='cut'>-</a>"+newid+"</td>"+
"<td>"+
"<ajaxToolkit:ComboBox ID='prod"+newid+"' runat='server' DataSourceID='SqlDataSource2' DataTextField='pname' DataValueField='pid' MaxLength='0' style='display: inline;'></ajaxToolkit:ComboBox>" +
"</td>"+
"<td><input type='number' required='required' min='1' name='quantity" + newid + "' /></td>" +
"<td id='price" + newid + "'></td>" +
"<td id='amount" + newid + "'></td>";
document.getElementById("table").appendChild(newcolumn);
}
I am doing this to get the values of all the elements in the code behind file to put them in database.
but due to this i get an error in the aspx.designer.cs page saying semicolon expected
protected global::AjaxControlToolkit.ComboBox prod" + newid + ";
ASP.NET Code
<table class="Grid" id="table">
<tr>
<td colspan="5">Enter Order Details</td>
</tr>
<tr>
<th>Sr No.</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
<tr id="1">
<td><a class="cut">-</a>1</td>
<td>
<ajaxToolkit:ComboBox ID="prod1" runat="server" DataSourceID="SqlDataSource2" DataTextField="pname" DataValueField="pid" MaxLength="0" style="display: inline;"></ajaxToolkit:ComboBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:micoConnectionString %>" SelectCommand="SELECT [pid], [pname] FROM [Products]"></asp:SqlDataSource>
</td>
<td><input type="number" required="required" min="1" name="quantity1" /></td>
<td id="price1"></td>
<td id="amount1"></td>
</tr>
</table>
<a class="add" onclick="addnewrow()" href="#">+</a>
Check this
$("#btnAddSchedule").click(function () {
var trs = $("[id^=trSchedules]");
var numberofrows = trs.length;
var newtr = $('#' + trs[0].id).clone();
$(newtr).attr('id', $(newtr).attr('id').replace(/\d+/, numberofrows));
newtr.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, numberofrows));
$(this).attr('name', $(this).attr('name').replace(/\d+/, numberofrows));
if ($(this).attr('type') != "hidden") {
$(this).val('');
}
else if ($(this).attr('id').indexOf('DataExportQueueID') == -1) {
$(this).val('');
}
if ($(this).attr("type") == "checkbox") {
$(this).removeAttr("checked");
$(this).parent().html($(this).parent().html().replace(/\d+/g, numberofrows));
}
if ($(this).attr("type") == "button") {
$(this).attr("onclick", "deleteSchedule(this,0);");
}
});
$('#' + trs[numberofrows - 1].id).after(newtr);
CrossCheckScheduleRows();
});
function CrossCheckScheduleRows() {
$('[id^=trSchedules]').each(function () {
var row = $(this);
var index = row[0].rowIndex - 2;
row.attr('id', row.attr('id').replace(/\d+/, index));
row.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, index)).attr('name', $(this).attr('name').replace(/\d+/, index));
});
});
}
I use this for the same purpose, maybe it will help you
I am currently working on a dynamic invoice system for myself. But I can't seem to completely get it working correctly.
I have a invoice table like this in HTML:
Product name -- Quantity -- Tax -- Price (without tax) -- total price
My HTML looks like this:
<td><input type="text" placeholder="Item name" class="form-control" /></td>
<td class="text-center"><input type="number" min="1" id="target" placeholder="Quantity" class="form-control quantity" /></td>
<td class="text-center"><input type="text" placeholder="TAX" class="form-control tax" /></td>
<td class="text-right"><input type="text" placeholder="Price" class="form-control" /></td>
<td class="text-right"><input type="text" disabled placeholder="0,00" class="form-control price" /></td>
I can add rows with this Javascript code:
<script>
function addItem(){
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control price" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table tr:last").after(itemRow);
}
</script>
And I calculate it with this jQuery code:
<script>
var total = 0;
var taxTotal = 0;
(function() {
$('#items_table').on('change', 'input', function() {
if( !$(this).hasClass('tax')) {
totalPrice = 0;
var row = $(this).closest('tr');
// ## Get quantity
var qty = parseFloat(row.find('input:eq(1)').val());
if (qty < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Get the entered price
var price = parseFloat(row.find('input:eq(3)').val());
if (price < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Calculate total price
var total = qty * price;
// ## Set total price at the end
row.find('input:eq(4)').val(isNaN(total) ? '' : total);
tax = parseFloat(row.find('input:eq(2)').val());
var salesTax = total * (tax / 100);
if (!isNaN(salesTax)) {
$('#tax-' + row.find('input:eq(2)').val()).html(salesTax.toFixed(2));
$('#tax_percentage').html(tax + '%');
$('#tax_total').html('€ ' + salesTax.toFixed(2));
$('.price').each(function (i, obj) {
// ## Add all the prices again
totalPrice = totalPrice += parseFloat($(this).val()) + salesTax;
});
}
$('#total_price').html('€ ' + totalPrice.toFixed(2));
}else{
// ## Remove all the taxes
$('[id^=tax-tr-]').remove();
if($('#tax-'+ $(this).val()).length > 0 ){
console.log('it already exists');
}else{
$('.tax').each(function (i, obj) {
var itemRow =
'<tr id="tax-tr-' + $(this).val() + '">' +
'<td colspan="4" class="font-w600 text-right">BTW ' + $(this).val() + '%</td>' +
'<td style="width: 20%;" class="text-right">€ <span id="tax-' + $(this).val() + '">0</span></td>' +
'</tr>';
$("#subtotal_table tr").eq(-2).after(itemRow);
});
}
}
});
})();
</script>
Although, its not exactly doing what I want. I want the total price to be at the end of the table row (total price disabled row)
And I want the tax to be added below the invoice (a new table), like this:
Sub total: (Total price without tax)
TAX 10%: (The tax ammount according to the 10%)
TAX 15%: (The tax ammount according to the 15%)
Total: (Sub total price + the tax prices)
But the problem I get is once I have 2 items in the table, and I change the first row's TAX, it gets all messed up.
I am currently out of idea's how to correctly do this. So I all I need is once I filled 1 item row, the tax gets in the total table added, and once I change that tax in that row, it changes below aswell, and the price has to be changed aswell.
Can someone get me back on the right track?
It's not exactly clear what you want to display in the second table,however, I believe the below will suite your needs.
Here is a jsFiddle as well
$('#addRow').click(function () {
addItem();
});
$('#items_table').on('keyup', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function addItem() {
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
<p>Add rows and give them values for quantity and price, the script will do the rest.</p>
<p>Select a diferent tax amount to recalculate everything</p>
I have a table which has one row in which I multiply two fields, namely quantity and rate/quantity, to get the product total. I have provided a button to add a new row which basically clones the 1st row. Now I want the cloned row to also have the same product as the 1st row. I have tried the following code:
<!DOCTYPE html>
<html>
<h3 align="center">K J Somaiya College Of Engineering, Vidyavihar, Mumbai-400 077</h3>
<h3 align="center">Department Of Information Technology</h3>
<body>
<script>
function WO1() {
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice').value = answer;
}
function WO2() {
var qty = document.getElementById('qty1').value;
var price = document.getElementById('price1').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice1').value = answer;
}
function WO3() {
var qty = document.getElementById('qty2').value;
var price = document.getElementById('price2').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice2').value = answer;
}
</script>
<script>
function validateNumbe()
{
var x=document.getElementById("floor").value;
if (x==null || x=="")
{
alert("Floor must be entered");
return false;
}
}
function validateN()
{
var x=document.getElementById("lab").value;
if (x==null || x=="")
{
alert("Laboratory Name must be entered");
return false;
}
}
function validateNumb()
{
var x=document.getElementById("room").value;
if (x==null || x=="")
{
alert("Room No must be entered");
return false;
}
}
function validateNum()
{
var x=document.getElementById("labi").value;
if (x==null || x=="")
{
alert("Name of Laboratory Incharge must be entered");
return false;
}
}
function validateNu()
{
var x=document.getElementById("year").value;
if (x==null || x=="")
{
alert("Budget for the year must be entered");
return false;
}
}
</script>
<table width="100%" cellspacing="10">
<tr>
<td align="left">Date:<input type="date" name="date"/></td>
<td align="right">Floor: <input type="text" id="floor" onchange="validateNumbe()"
onblur="validateNumbe()"/> </td>
</tr>
<tr>
<td align="left">Laboratory Name: <input type="text" id="lab" onchange="validateN()"
onblur="validateN()"/></td>
<td align="right">Room no: <input type="text" id="room" onchange="validateNumb()"
onblur="validateNumb()"/></td>
</tr>
<tr>
<td align="left">Name of Laboratory Incharge: <input type="text" id="labi"
onchange="validateNum()" onblur="validateNum()"/></td>
<td align="right">Budget for the year: <input type="text" id="year" onchange="validateNu()"
onblur="validateNu()"/></td>
</tr>
</table>
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<td style="width:10%">Sr No.</td>
<td>Item Description</td>
<td>Quantity</td>
<td>Rate(Inclusive of Taxes)</td>
<td>Total Cost</td>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price' class="price" placeholder='Price (£)'
onChange="WO1()" /></td>
<td><input type='text' name='Total' id='totalprice' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<h3 align="left"><b>Equipment</b><h3>
<table id="POITable1" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty1' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price1' class="price" placeholder='Price (£)'
onChange="WO2()" /></td>
<td><input type='text' name='Total' id='totalprice1' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton1" value="Add New Row"/>
<h3 align="left"><b>Furniture</b><h3>
<table id="POITable2" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty2' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price2' class="price" placeholder='Price (£)'
onChange="WO3()" /></td>
<td><input type='text' name='Total' id='totalprice2' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton2" value="Add New Row"/>
<script>
( function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
}
var formTable1 = document.getElementById('POITable1');
var newRowBtn1 = document.getElementById('addmorePOIbutton1');
newRowBtn1.addEventListener('click', insRow1, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow1() {
var new_row = formTable1.rows[1].cloneNode(true),
numTableRows = formTable1.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable1.appendChild( new_row );
}
var formTable2 = document.getElementById('POITable2');
var newRowBtn2 = document.getElementById('addmorePOIbutton2');
newRowBtn2.addEventListener('click', insRow2, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow2() {
var new_row = formTable2.rows[1].cloneNode(true),
numTableRows = formTable2.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable2.appendChild( new_row );
}
})();
function myfun()
{
var lun= document.getElementById('POITable').rows.length;
document.getElementsByName("len")[0].value = lun-1;
var lun1= document.getElementById('POITable1').rows.length;
document.getElementsByName("len1")[0].value = lun1-1;
var lun2= document.getElementById('POITable2').rows.length;
document.getElementsByName("len2")[0].value = lun2-1;
}
function myFunction()
{
window.print();
}
</script>
<input type="hidden" name="len" value="1">
<input type="hidden" name="len1" value="1">
<input type="hidden" name="len2" value="1">
<table width="100%">
<tr>
<td><br><br><br></td>
<td><br><br><br></td>
<td><br><br><br></td>
</tr>
<tr>
<td align="left">Signature <br>Lab-In-Charge</td>
<td align="center">Signature<br>Lab Assistant</td>
<td align="right">Signature <br>Head of Department</td>
</tr>
</table>
<br><br><br>
<input type="submit" value="SUBMIT" onclick='this.form.action="archive.php";myfun();'>
<input type="submit" value="SAVE AND CONTINUE LATER"
onclick='this.form.action="myphpformhandler.php";myfun();'>
</form>
<h3 align="center"><button onclick="myFunction()"><h3>Print this page</h3></button></h3>
</body>
</html>
i have created the JSFiddle but the multiplication is not working in it.
http://jsfiddle.net/xkY4Z/2/
Not a perfect solution to your problem but a bit closer Working Fiddle
Done using jQuery
$(document).on('change','input', function () {
var id = $(this).attr('id').split("-");
var answer = (Number($('#qty-' + id[1]).val()) * Number($('#price-' + id[1]).val())).toFixed(2);
$('#totalprice-' + id[1]).val(answer);
});
Update
Working Fiddle with name
Latest
Fiddle with Grand total