Dropdown data-attributes to populate into input fields on dynamically added rows - javascript

**This is the code i currently come up with I wanted to populate price and tax files from data- attributes **
<table class="table g-5 gs-0 mb-0 fw-bolder text-gray-700" id="tab_logic">
<!--begin::Table head-->
<thead>
<tr class="border-bottom fs-7 fw-bolder text-gray-700 text-uppercase">
<th class="min-w-50px w-50px">#</th>
<th class="min-w-300px w-475px">Item</th>
<th class="min-w-100px w-100px">QTY</th>
<th class="min-w-100px w-100px">Price</th>
<th class="min-w-100px w-100px">Tax</th>
<th class="min-w-100px w-100px text-end">Total</th>
<th class="min-w-75px w-75px text-end">Action</th>
</tr>
</thead>
<!--end::Table head-->
<!--begin::Table body-->
<tbody>
<tr class="border-bottom border-bottom-dashed" id='addr1'>
<td class="pt-8 text-nowrap rowid" >1</td>
<td class="pe-7">
<select class="form-control form-control-solid itemname" name="itemname[]">
#foreach($items as $item)
<option data-rate="{{$item->item_price }}" data-tax="{{$item->item_tax }}">{{$item->item_name}}</option>
#endforeach
</select>
</td>
<td class="ps-0"><input type="number" class="form-control form-control-solid qty" min="1" name="quantity[]" placeholder="0" /></td>
<td><input type="number" class="form-control form-control-solid price" name="price[]" min="1" placeholder="0.00" /></td>
<td><input type="number" class="form-control form-control-solid text-end tax" name="tax[]" min="0" placeholder="0.00" /></td>
<td><input type="text" class="form-control form-control-solid text-end total" name="total[]" min="1" placeholder="0.00" /></td>
<td class="pt-5 text-end">
<button class="btn btn-sm btn-icon btn-active-color-primary" id="removeRow">Remove</button>
</td>
</tr>
</tbody>
</table>
Add dynamic rows to the table
<script>
$(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++;
});
$(document).on('click', '#removeRow', function () {
if(i>1){
$(this).parent().parent().remove();
i--;
}
calc();
});
</script>
Populate price and tax fields from data attributes
<script>
$(document).ready(function() {
$('tr .itemname').change(function(){
var selected = $('option:selected', this);
// this should now output the correct product name and its rate.
console.log(selected.data('tax'), selected.data('rate') );
// now to add it to rate field within this TR
$(this).parent().parent().find('.price').val( selected.data('rate') );
$(this).parent().parent().find('.tax').val( selected.data('tax') );
});
});
</script>
When select the item first row data populate correctly. However when dynamically add a new row to table and select item its not getting the price and tax values.

I´m not quite sure if this will actually fix it but there is 1 obvious error in your code.
this line
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
appends the tr´s to the table but it should append the tr´s to tbody, so change it to
$('#tab_logic tbody').append('<tr id="addr'+(i+1)+'"></tr>');
i guess your .parent().parent()... works for the first item correctly because it´s in tbody and for the new added not

Related

Select elements within target div (row) on event jQuery

I have a table from which I need to select all of the values of the row after an event done in the same row (in this case is a keyup event) with jQuery. The table could have many rows but the selection has to be on the items of the row event.
This is the HTML of the table:
<table class="table" id="form-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Description</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
<th scope="col">Discount</th>
<th scope="col">Amount</th>
<th scope="col">Hidden</th>
</tr>
</thead>
<tbody>
<tr id="row-1">
<th scope="row">1</th>
<td class="description-column">
<div class="form-group">
<select class="form-control" id="companySelect">
{% for product in product_options %}
<option>{{ product }}</option>
{% endfor %}
</select>
</div>
</td>
<td class="qty-column">
<div class="form-group">
<input type="number" class="form-control" id="qty" placeholder="Qty" min="0" step="1">
</div>
</td>
<td class="price-column">
<div class="form-group">
<input type="number" class="form-control" id="price" min="0.01" placeholder="Price">
</div>
</td>
<td class="discount-column">
<div class="form-group">
<input type="number" class="form-control" id="discount" placeholder="0" min="0.01" max="99.99">
</div>
<div>%</div>
</td>
<td class="amount-column"></td>
<td class="hidden-column">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="hiddenCheck">
</div>
</td>
</tr>
</tbody>
</table>
And looks like this on the site:
For more context: I am making a quote app in which I'll type the price and quantity of each item in each row and I need to update the "amount" column after each keyup. So I need to know how to select the proper "qty", "price", "discount" and "amount" id's of the row typed to do that.
Firstly, The id attribute is unique, So you should replace it with class like this
<input type="number" class="form-control qty" placeholder="Qty" min="0" step="1">
Secondly, You can get the tr by using .closest() like this $(this).closest("tr")
Finally, You can calculate individual row by creating another method named updateAmount_per_row like below:
function updateAmount_per_row(tr){
var qTy = getValue_by_className(tr, '.qty-column .qty');
var price = getValue_by_className(tr, '.price-column .price');
var amount = qTy * price;
tr.find('.amount-column').html(amount);
}
$(".qty-column, .price-column").on("keyup", function(){
var tr = $(this).closest("tr");
updateAmount_per_row(tr);
});
function updateAmount_per_row(tr){
var qTy = getValue_by_className(tr, '.qty-column .qty');
var price = getValue_by_className(tr, '.price-column .price');
var amount = qTy * price;
tr.find('.amount-column').html(amount);
}
function getValue_by_className(tr, className){
var value = parseInt(tr.find(className).val(), 10);
return value >= 0 ? value : 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="form-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Description</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
<th scope="col">Discount</th>
<th scope="col">Amount</th>
<th scope="col">Hidden</th>
</tr>
</thead>
<tbody>
<tr id="row-1">
<th scope="row">1</th>
<td class="description-column">
<div class="form-group">
<select class="form-control" class="companySelect">
<option>Product A</option>
<option>Product B</option>
</select>
</div>
</td>
<td class="qty-column">
<div class="form-group">
<input type="number" class="form-control qty" placeholder="Qty" min="0" step="1">
</div>
</td>
<td class="price-column">
<div class="form-group">
<input type="number" class="form-control price" min="0.01" placeholder="Price">
</div>
</td>
<td class="discount-column">
<div class="form-group">
<input type="number" class="form-control" class="discount" placeholder="0" min="0.01" max="99.99">
</div>
<div>%</div>
</td>
<td class="amount-column"></td>
<td class="hidden-column">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="hiddenCheck">
</div>
</td>
</tr>
<tr id="row-2">
<th scope="row">2</th>
<td class="description-column">
<div class="form-group">
<select class="form-control" class="companySelect">
<option>Product A</option>
<option>Product B</option>
</select>
</div>
</td>
<td class="qty-column">
<div class="form-group">
<input type="number" class="form-control qty" placeholder="Qty" min="0" step="1">
</div>
</td>
<td class="price-column">
<div class="form-group">
<input type="number" class="form-control price" min="0.01" placeholder="Price">
</div>
</td>
<td class="discount-column">
<div class="form-group">
<input type="number" class="form-control" class="discount" placeholder="0" min="0.01" max="99.99">
</div>
<div>%</div>
</td>
<td class="amount-column"></td>
<td class="hidden-column">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="hiddenCheck">
</div>
</td>
</tr>
</tbody>
</table>
Using Mai Phuong answer as testing I managed to make it work by using the target property instead of this, because this for some reason was referencing the whole document (#document).
Here is the keyup event listener:
$('.price, .qty, .discount').keyup((event) => {
let tr = event.target.closest('tr');
updateAmount(tr);
});
and here's the final updateAmount function:
function updateAmount(tr) {
let qty = $(tr).find('.qty').val();
let price = $(tr).find('.price').val();
let discount = $(tr).find('.discount').val();
let amount = (qty * price * (100 - discount)) / 100;
$(tr).find('.amount').html(amount);
}

How to pick the date using date picker in dynamic table?

My problem is how to use date picker in dynamic rows of the column.
I have used date picker in input text field,but it appears only in first row of the date column.
By selecting the date the date is not selected.
<table class="table table-bordered table-striped table-xxs" id="tb3">
<thead>
<tr>
<th></th>
<th>Bank Name</th>
<th>Chq No</th>
<th>Chq Date</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr >
<td><a href='javascript:void(0);' class='remove3'><span class='glyphicon glyphicon-remove'></span></a></td>
<td>
<input style="width:100px" type="text" id="Product_Code" class="form-control input-xs Product_Code "name="name[]"></td>
<td ><input style="width:100px" type="text" id="Product_Name" class="form-control input-xs" name = "no[]" > </td>
<td><input type="text" class="form-control input-xs datepicker-dates" placeholder="Pick a date…" id="TDate" name="TDate" value="<?php echo date('d/m/Y') ?>"</td>
<td><input style="width:80px" type="text" id="Rate" class="form-control input-xs" value="" name="rate[]"></td>
<td><a href="javascript:void(0);" style="font-size:18px;" id="addMore3" title="Add More Person"><span class="glyphicon glyphicon-plus"></td>
</tr>
</tbody>
</table>
This is table code...........
<script>
$(function(){
$('#addMore3').on('click', function() {
var data = $("#tb3 tr:eq(1)").clone(true).appendTo("#tb3");
data.find("input").val('');
});
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
});
</script>
This is javascript code for creating dynamic rows and columns.
try this:
<input type="text" name="TDate" class="form-control" value="" id="datepicker">
<script type="text/javascript">
$(function () {
$('#datepicker').datepicker();
});</script>

Apply function in dynamically added each row differently with jQuery

I have added new rows dynamically with jQuery and applied a function but I want to apply this differently for each row. right now its applying commonly for every rows.
HTML code:
<button type="button" id="addBankRow" >add</button>
<table class="table table-bordered" id="dynamic_field_bank">
<thead>
<tr>
<th width="10%">Deposit Date</th>
<th width="10%">Deposit Method</th>
<th width="25%">Bank Title</th>
<th width="25%">Account No</th>
<th width="20%">Deposit Amount</th>
<th width="10%">#</th>
</tr>
</thead>
<tbody>
<tr class="bank_deposit">
<td><p>12/10/17</p></td>
<td>
<select class="form-control" id="deposit_method">
<option>Bank</option>
<option>Vault</option>
</select>
</td>
<td><input id="bank_title" name="bank_title" required="required" type="text"></td>
<td>
<select class="form-control" id="bank_ac_no">
<option>151035654646001</option>
<option>151035654646002</option>
<option>151035654646003</option>
</select>
</td>
<td><input id="deposit_amount" name="deposit_amount" required="required" type="number" min="0"></td>
<td>
</td>
</tr>
</tbody>
</table>
Jquery Codes:
var i=1;
$('#addBankRow').click(function(){
i++;
$('#dynamic_field_bank').append('<tr id="row'+i+'" class="dynamic-added" ><td><p>12/10/17</p></td><td><select class="form-control" id="deposit_method"><option>Bank</option><option>Vault</option></select></td><td><input id="bank_title" name="bank_title" required="required" type="text"></td><td><select class="form-control" id="bank_ac_no"><option>151035654646001</option><option>151035654646002</option><option>151035654646003</option></select></td><td><input id="deposit_amount" name="deposit_amount" required="required" type="number" min="0"></td><td>X</td></tr>');
});
$(document).on('click', '.btn_remove', function(e){
e.preventDefault();
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("tbody").on('change', "#deposit_method", function() {
if ($(this).val() == 'Vault'){
$('#bank_title, #bank_ac_no').hide();
}
else if ($(this).val() == 'Bank'){
$("tr.bank_deposit").each(function (){
$('#bank_title, #bank_ac_no').show();
});
}
});
When I am changing the deposit method I want to hide/show the two fields in each row but its applying in every row.
see the demo with codes:
https://jsfiddle.net/wasid/33qp9ewn/3/
You can add an attribute (like row-id) for inputs to determine which row has been processed. I modified HTML and Javascript codes. Also, you can take a look modifed codes as Fiddle Demo
HTML
<button type="button" id="addBankRow" >add</button>
<table class="table table-bordered" id="dynamic_field_bank">
<thead>
<tr>
<th width="10%">Deposit Date</th>
<th width="10%">Deposit Method</th>
<th width="25%">Bank Title</th>
<th width="25%">Account No</th>
<th width="20%">Deposit Amount</th>
<th width="10%">#</th>
</tr>
</thead>
<tbody>
<tr class="bank_deposit">
<td><p>12/10/17</p></td>
<td>
<select class="form-control" id="deposit_method" row-id="0">
<option>Bank</option>
<option>Vault</option>
</select>
</td>
<td><input id="bank_title" name="bank_title" required="required" type="text" row-id="0"></td>
<td>
<select class="form-control" id="bank_ac_no" row-id="0">
<option>151035654646001</option>
<option>151035654646002</option>
<option>151035654646003</option>
</select>
</td>
<td><input id="deposit_amount" name="deposit_amount" required="required" type="number" min="0" row-id="0"></td>
<td>
</td>
</tr>
</tbody>
</table>
Javascript;
var i=1;
$('#addBankRow').click(function(){
i++;
$('#dynamic_field_bank').append('<tr id="row'+i+'" class="dynamic-added" ><td><p>12/10/17</p></td><td><select class="form-control" id="deposit_method" row-id="'+i+'"><option>Bank</option><option>Vault</option></select></td><td><input id="bank_title" name="bank_title" required="required" type="text" row-id="'+i+'"></td><td><select class="form-control" id="bank_ac_no" row-id="'+i+'"><option>151035654646001</option><option>151035654646002</option><option>151035654646003</option></select></td><td><input id="deposit_amount" name="deposit_amount" required="required" type="number" min="0" row-id="'+i+'"></td><td>X</td></tr>');
});
$(document).on('click', '.btn_remove', function(e){
e.preventDefault();
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("tbody").on('change', "#deposit_method", function() {
var rowId = $(this).attr("row-id");
if ($(this).val() == 'Vault'){
$("#bank_title[row-id='"+rowId+"'], #bank_ac_no[row-id='"+rowId+"']").hide();
}
else if ($(this).val() == 'Bank'){
$("#bank_title[row-id='"+rowId+"'], #bank_ac_no[row-id='"+rowId+"']").show();
}
});

How to calculate sum of dynamically row adding table

I have a table,it can add dynamical rows.what i'm trying to do is,calculate amount column sum and display in Expences field.then reduce expencess from income and display total in balance field
eg:
when user fill first row with book and price for book in amount column.then click add item button and add another row.that time calculate sum of book and pen and display in expences field.total will display balance field.
<div class="col-xs-12">Income (Rs) : <input type="number" min="0.01" step="0.01" name="income" value="2536.67" id="income" >
</div>
<div class="col-xs-12">Expences (Rs) : <input type="number" min="0.01" step="0.01" name="expence" value="" readonly id="expence">
</div>
<div class="col-xs-12">Balance (Rs) : <input type="number" min="0.01" step="0.01" name="balance" value="" readonly id="balance">
</div>
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Category
</th>
<th class="text-center">
Item Name
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<select class="form-control" name="cat">
<option value="bill">Bill</option>
<option value="exchange">Exchange</option>
</select>
</td>
<td>
<input type="text" name='name0' placeholder='Item Name' class="form-control"/>
</td>
<td class='amount'>
<input type="number" name='amount' placeholder='Amount' class="form-control" id='amount'/>
</td>
<td>
<input type="file" class="form-control" name="upload" />
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<a id="add_row" class="btn btn-default pull-left">Add Item</a><a id='delete_row' class="pull-right btn btn-default">Delete Item</a>
<button type="Submit" class="btn btn-success pull-right btn-lg" >Submit</button>
Add,delete row query
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select class='form-control' name='cat"+i+"'><option value='bill'>Bill</option><option value='exchange'>Exchange</option></select><td><input name='name"+i+"' type='text' placeholder='Item Name' class='form-control input-md' /> </td><td class='amount'><input name='mail"+i+"' type='number' min='0.01' step='0.01' placeholder='Amount' id='amount"+i+"' class='form-control input-md'></td><td><input type='file' name='upload"+i+"' class='form-control'/></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
i tried this query.this is cal from table td class.
$(document).ready(function(){
$('.amount').each(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
$(".amount").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$('#expence').text(sum);
};
This might be because, your function calculateSum(); isn't triggering. You can probably use .change to check, if any value changed for this class and then calculate the sum.
$( ".amount" ).change(function (){
var sum=0;
$('.amount').each(function(i, obj){
if($.isNumeric(this.value)) {
sum += parseFloat(this.value);
}
})
$('#expence').val(sum);
});
>>Demo<<
Try the below code, it will work for dynamic elements too, just ensure that they have class name amount:
$(".amount").on('change', calculate);
function calculate() {
var sum = 0;
$('.amount').each(function(i, obj) {
if ($.isNumeric(this.value)) {
sum += parseFloat(this.value);
}
});
$('#expense').val(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Amount : <input type="text" class="amount"><br/> Amount : <input type="text" class="amount"><br/> Amount : <input type="text" class="amount"><br/> Expense : <input type="text" id="expense">

Do SUM of Dynamic row added by innerHTML method through javascript

I am trying to do Sum on oninput method. Means as the button press the function will be called and show sum of two input in a paragraph <p> tag.
I have my javascript function like this:
quote:function(){
var button = document.getElementById('insert');
var table = document.getElementById('table');
$("#insert").click(function(){
var position=Math.round(table.rows.length - 3);
var row = table.insertRow(position);
var i=1;
row.innerHTML = '<td><input type="integer" name="qty[]" class="form-control" id="qty_' +position +'" oninput="myFunction(demo'+position+', event)"></td><td><input type="text" name="discription[]" class="form-control"></td><td><input type="text" name="price[]" class="form-control" placeholder="0.00" id="price_'+ position+'" oninput="myFunction(demo'+position+', event)"></td><td><input type="text" name="discount[]" class="form-control" placeholder="0.00"><td><input type="text" name="discountper[]" class="form-control" placeholder="0.00%"></td></td><td><p id="demo'+position+'"></p></td><td><input type="checkbox" name="taxed[]" class="form-control"></td> <td><a class="btn btn-circle red-haze btn-sm" href="javascript:void(0);" id="remCF"><i class="fa fa-times"></i></a></td>';
$("#remCF").live('click',function(){
$(this).parent().parent().remove();
});
});
},
After append it looks like this.
I would like to calculate Total Amount using quantity * price.
But i am not able to do that. It seems like Rows are appending fine. But when i try to call the function i am unable to specify the text are in the myFunction.
here is how myFuntion looks like:
function myFunction(place, event) {
var x =parseInt(document.getElementById(event.target.id).value); <!----now the problem is here i am not able to specify what QTY is clicked and which input is clicked -->
var y= parseInt(document.getElementById(event.target.id).value); <!----now the problem is here i am not able to specify what PRICE is clicked and which input is clicked -->
var z=x*y;
document.getElementById(place).innerHTML = z;
}
I would like to perform calculation row wise.
And if for reference if you want to know how my HTML looks then here is how it looks like.
<table class="table table-striped table-bordered table-hover" id="sample_3">
<thead>
<tr>
<th style="width:7%;">
Qty
</th>
<th style="width:50%;">
Description
</th>
<th style="width:10%;">
Unit Price
</th>
<th style="width:10%;">
Discount(Rs/$)
</th>
<th style="width:10%;">
Discount%
</th>
<th style="width:7%;">
Total
</th>
<th style="width:2%;">
Taxed
</th>
<th style="width:2%;">
Action
</th>
</tr>
</thead>
<tbody id="table">
<tr class="odd gradeX" id="p_scents" name="p_scnt">
<td>
<input type="integer" name="qty[]" class="form-control" value="1" id="myInput1" oninput="myFunction('demo', event)" >
</td>
<td>
<input type="text" name="discription[]" class="form-control">
</td>
<td>
<input type="text" name="price[]" class="form-control" placeholder="0.00" id="myInput2" oninput="myFunction('demo', event)">
</td>
<td>
<input type="text" name="discount[]" class="form-control" placeholder="0.00">
</td>
<td>
<input type="text" name="discountper[]" class="form-control" placeholder="0.00%">
</td>
<td>
<p id="demo"></p>
</td>
<td>
<div align="center"><input type="checkbox" name="taxed[]" class="form-control"></div>
</td>
<td></td>
</tr><!-- to add new column -->
<tr>
<td colspan="4" >
<div align="right">
<b>Sub Total:</b>
</div>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="6" >
<a id="insert">Add a New Service</a><br>
<a id="ajax-demo" data-toggle="modal">
Predifined Services </a><td>
</tr>
</tbody>
</table>
here is the Jsfiddle link:
https://jsfiddle.net/5xaaneor/2/
Thank you!

Categories