Jquery add more and delete conflicting and shows wrong value - javascript

Jquery add more and delete conflicting and shows wrong value
When i add more rows working fine like 1-2-3-4
But when i delete one row then it again add 1-2-3-3
and when i delete two rows then it shows 1-4-3-4
I want this properly working i try too methods but no luck
$(function() {
var scntDiv = $('#pmore');
var i = $('#pmore tr').size() + 1;
$('.addmore').on('click', function() {
$('<tr><td align="center">' + i + '</td><td><input type="text" data-type="productName" name="itemName[]" id="itemName_' + i + '" class="form-control autocomplete_txt" ></td><td><input type="number" name="price[]" id="price_' + i + '" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td><td><input type="number" name="quantity[]" id="quantity_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td><td><input type="number" name="total[]" id="total_' + i + '" class="form-control totalLinePrice" autocomplete="off" readonly></td><td><button class="btn btn-danger" id="dlt" type="button">- Delete</button></td><td></td></tr>').appendTo(scntDiv);
i++;
return false;
});
$(document).on('click', '#dlt', function() {
if (i > 2) {
$(this).parents('tr').remove();
i--;
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table width="100%" class="table table-striped table-bordered dataTable">
<thead>
<tr>
<th width="5%">S no</th>
<th width="35%">Part Name</th>
<th width="10%">Price</th>
<th width="10%">Quantity</th>
<th width="10%">Total</th>
<th width="30%" colspan="2">Action</th>
</tr>
</thead>
<tbody id="pmore">
<tr>
<td align="center">1</td>
<td>
<input type="text" data-type="productName" name="itemName[]" id="itemName_1" class="form-control autocomplete_txt" required>
</td>
<td>
<input type="number" name="price[]" id="price_1" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</td>
<td>
<input type="number" name="quantity[]" id="quantity_1" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</td>
<td>
<input type="number" name="[total]" id="total_1" class="form-control totalLinePrice" readonly>
</td>
<td align="center">
<button class="btn btn-success addmore" type="button">+ Add More</button>
</td>
<td align="center">
<button class="btn btn-danger dlt" type="button">- Delete</button>
</td>
</tr>
</tbody>
</table>

When you remove an item, you need to make sure that the following items indexes are reduced by 1
$(function() {
var scntDiv = $('#pmore');
var i = $('#pmore tr').size() + 1;
$('.addmore').on('click', function() {
$('<tr><td align="center">' + i + '</td><td><input type="text" data-type="productName" name="itemName[]" id="itemName_' + i + '" class="form-control autocomplete_txt" ></td><td><input type="number" name="price[]" id="price_' + i + '" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td><td><input type="number" name="quantity[]" id="quantity_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td><td><input type="number" name="total[]" id="total_' + i + '" class="form-control totalLinePrice" autocomplete="off" readonly></td><td><button class="btn btn-danger" id="dlt" type="button">- Delete</button></td><td></td></tr>').appendTo(scntDiv);
i++;
return false;
});
$(document).on('click', '#dlt', function() {
if (i > 2) {
var $tr = $(this).closest('tr');
$tr.nextAll().find('td:first-child').text(function(i, text) {
return --text;
});
$tr.remove();
i--;
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table width="100%" class="table table-striped table-bordered dataTable">
<thead>
<tr>
<th width="5%">S no</th>
<th width="35%">Part Name</th>
<th width="10%">Price</th>
<th width="10%">Quantity</th>
<th width="10%">Total</th>
<th width="30%" colspan="2">Action</th>
</tr>
</thead>
<tbody id="pmore">
<tr>
<td align="center">1</td>
<td>
<input type="text" data-type="productName" name="itemName[]" id="itemName_1" class="form-control autocomplete_txt" required>
</td>
<td>
<input type="number" name="price[]" id="price_1" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</td>
<td>
<input type="number" name="quantity[]" id="quantity_1" class="form-control changesNo" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</td>
<td>
<input type="number" name="[total]" id="total_1" class="form-control totalLinePrice" readonly>
</td>
<td align="center">
<button class="btn btn-success addmore" type="button">+ Add More</button>
</td>
<td align="center">
<button class="btn btn-danger dlt" type="button">- Delete</button>
</td>
</tr>
</tbody>
</table>

Related

My function validation does not work on added row

I have a function where my input type="number" data-id="weight" checks whether the user typed a divisible by 5 or not. It is perfectly working on my current row but when i add a new row/s, it is not working. Is there anything i missed? I provided my snippet below. Thank you everyone.
To try it. Please type on the weight column a number that is not divisible by 5, then you'll see the error. Add row and do the same, you will not see the error. My target is my function to work with added rows too.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight' + rowIndex + '" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
// divisible by only 5
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', () => {
if (input.value % 5 !== 0) {
alert('not valid');
input.value = 5;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
This is caused by the event handler for the change event not being fired for dynamically created objects.
When you create an the event handlers like this:
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', () => {
...
}
});
The handler is only mapped for elements that exist when you first run the code. That means any subsequently created dynamic elements will not cause the event to fire.
Instead, use the following syntax to create the event which will catch dynamically created elements by using their selector (input[data-id="weight"]):
$(document).on('change', 'input[data-id="weight"]', function(e) {
if ($(this).val() % 5 !== 0) {
alert('not valid');
$(this).val(5);
}
});
I've removed the other code you had previously that tried to bind the event handler. You don't need to do it that way with jQuery.
Seen here in a working version of your snippet:
$("#addrow").on('click', function(){
let rowIndex = $('.auto_num').length+1;
let rowIndexx = $('.auto_num').length+1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="'+rowIndexx+'" /></td>"' +
'<td><input name="lightBand'+rowIndex+'" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight'+rowIndex+'" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand'+rowIndex+'" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow'+rowIndex+'" name="removerow'+rowIndex+'" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
// divisible by only 5
$(document).on('change', 'input[data-id="weight"]', function(e) {
if ($(this).val() % 5 !== 0) {
alert('not valid');
$(this).val(5);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto"/>
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove" >
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
Add change event listener after adding the table row. Modified the above code as below:
$("#addrow").on('click', function(){
let rowIndex = $('.auto_num').length+1;
let rowIndexx = $('.auto_num').length+1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="'+rowIndexx+'" /></td>"' +
'<td><input name="lightBand'+rowIndex+'" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input data-id="weight" name="weight'+rowIndex+'" type="number" placeholder="not working divisible by 5" /></td>"' +
'<td><input id="wingBand" name="wingBand'+rowIndex+'" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow'+rowIndex+'" name="removerow'+rowIndex+'" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
const list = document.querySelectorAll('input[data-id="weight"]');
const input = list[list.length - 1];
console.log(input)
input.addEventListener('change', inputValidation);
});
const inputValidation = (e) => {
if (e.target.value % 5 !== 0) {
alert('not valid');
e.target.value = 5;
}
}
// divisible by only 5
const inputer = document.querySelectorAll('input[data-id="weight"]');
inputer.forEach(input => {
input.addEventListener('change', inputValidation);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto"/>
</td>
<td class="labelcell">
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
<input data-id="weight" name="weight1" type="number" placeholder="Working divisible by 5" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove" >
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

How to get a multiple of two text box that is generate by dynamic input box

I want to multiply 2 input box (man_day_rates * estimated_man_days) but the input is dynamically generate and display it in subtotal.The problem is I only can calculate the first input, when i press add button, the second input does cannot calculate.
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row1'+i+'"><td style="border:none;"></td>\
<td style="border:none;">\
<input id="man_day_rates'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >\
</td>\
<td style="border:none;">\
<input id="estimated_man_days'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">\
</td>\
<td style="border:none;"> <input id="result2" type="text" name="" value=""/></td>\
<td style="height: 20px;line-height: 20px;white-space: nowrap; border:none;"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn_remove">X</button></td>\
</tr> ');
});
$(document).ready(function(){
var man_day_rates = $('#man_day_rates1');
var estimated_man_days = $('#estimated_man_days1');
estimated_man_days.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
man_day_rates.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table-responsive">
<table class="table table-striped" id="dynamic_field" style="padding:0px;">
<thead>
<tr class="headings">
<th class="column-title">#</th>
<th class="column-title">Item Title</th>
<th class="column-title">Description </th>
<th class="column-title" style="width:100px;">Man Day Rates (RM)</th>
<th class="column-title" style="width:100px;">Estimated Man Days </th>
<th class="column-title"style="width:100px;">Subtotal (RM)</th>
<th class="column-title"style="width:100px;"></th>
</th>
</tr>
</thead>
<tbody>
<tr id="row01">
<?php
$i = 1;
?>
<td style="border:none;">
<input id="man_day_rates<?php echo $i; ?>" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >
</td>
<td style="border:none;">
<input id="estimated_man_days<?php echo $i; ?>" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">
</td>
<td id=""> <input id="result" type="text" name="" value=""/></td>
<td class="add_remove_button" style="height: 20px;line-height: 20px;white-space: nowrap;"></td>
</tr>
</tbody>
</table>
</div>
<div><button id="add" type="button" class="btn btn-primary "><span class="fa fa-plus" style="margin-right:5px;"></span>Add Items</button></div>
I want to multiply 2 input box (man_day_rates * estimated_man_days) but the input is dynamically generate and display it in subtotal.The problem is I only can calculate the first input, when i press add button, the second input does cannot calculate.
you have to initialize your key event each time when you add new control dynamically.
Try like below.
$(document).ready(function(){
$('#add').click(function(){
i++;
//Add field document History
$('#dynamic_field').append('<tr id="row1'+i+'"><td style="border:none;"></td>\
<td style="border:none;">\
<input id="man_day_rates'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >\
</td>\
<td style="border:none;">\
<input id="estimated_man_days'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">\
</td>\
<td style="border:none;"> <input id="result2" type="text" name="" value=""/></td>\
<td style="height: 20px;line-height: 20px;white-space: nowrap; border:none;"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn_remove">X</button></td>\
</tr> ');
var man_day_rates = $('#man_day_rates'+i);
var estimated_man_days = $('#estimated_man_days'+i);
estimated_man_days.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
man_day_rates.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
});
});

How to get input value from each td after attribute readonly applied?

I built a script which is clone every child rows from the parent typing on a checkbox checked here.
It was working until now. I want each child input value to be saved by ajax. But only the last child is echoed.
JS
function cloneAllz(clsName) {
var $input1 = $('.prdEdt').find('td.' + clsName + ' input[type="text"]').filter(':visible:first'); //master input
//console.log($input1.attr('id'));//test master input
$input1.on('input', function() {
var $this = $(this);
window.setTimeout(function() {
if ($('input.' + clsName).is(':checked')) {
var $child = $('.prdEdt').find('td.' + clsName + ' input[type="text"]');
$child.val($this.val()).attr('readonly', true).each(function() { //how to loop each input in the column???
console.log($this.attr('id'));
});
$input1.attr('readonly', false);
} else {
$('.prdEdt').find('td.' + clsName + ' input[type="text"]').removeAttr('readonly', ); //remove readonly
}
}, 0);
});
}
HTML
<table class="table table-bordered table-striped prdEdt">
<tr>
<th>ID</th>
<th>Code
<label class="pull-right label label-default">
<input type="checkbox" class="cde" onChange="cloneAllz('cde')" /> <em class="fa fa-clone"></em></label>
</th>
<th>Title
<label class="pull-right label label-default">
<input type="checkbox" class="tt_en" onChange="cloneAllz('tt_en')" /> <em class="fa fa-clone"></em></label>
</th>
<th>Cost</th>
</tr>
<tr>
<td>00067</td>
<td class="cde">
<input type="text" name="prd_cde" id="prd_cde|67" class="form-control" value="3000009" />
</td>
<td class="tt_en">
<input type="text" name="prd_title_en" id="prd_title_en|67" class="form-control" value="TRANSFER KRABI AIRPORT-AO NANG" />
</td>
<td>
<input type="number" name="prd_cost" id="prd_cost|67" class="form-control" value="800" />
</td>
</tr>
<tr>
<td>00068</td>
<td class="cde">
<input type="text" name="prd_cde" id="prd_cde|68" class="form-control " value="3000009" />
</td>
<td class="tt_en">
<input type="text" name="prd_title_en" id="prd_title_en|68" class="form-control " value="TRANSFER KRABI AIRPORT-AO NANG " />
</td>
<td>
<input type="number" name="prd_cost" id="prd_cost|68" class="form-control" value="600" />
</td>
</tr>
</table>
So the question is : How to echo each row input to save them data via ajax???
function cloneAllz(clsName) {
var $input1 = $('.prdEdt').find('td.' + clsName + ' input[type="text"]').filter(':visible:first'); //master input
//console.log($input1.attr('id'));//test master input
$input1.on('input', function() {
var $this = $(this);
window.setTimeout(function() {
if ($('input.' + clsName).is(':checked')) {
var $child = $('.prdEdt').find('td.' + clsName + ' input[type="text"]');
$child.val($this.val()).attr('readonly', true).each(function() { //how to loop each input in the column???
console.log($this.attr('id'));//only first row echoed twice!
});
$input1.attr('readonly', false);
} else {
$('.prdEdt').find('td.' + clsName + ' input[type="text"]').removeAttr('readonly', ); //remove readonly
}
}, 0);
});
}
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-striped prdEdt">
<tr>
<th>ID</th>
<th>Code
<label class="pull-right label label-default">
<input type="checkbox" class="cde" onChange="cloneAllz('cde')" /> <em class="fa fa-clone"></em></label>
</th>
<th>Title
<label class="pull-right label label-default">
<input type="checkbox" class="tt_en" onChange="cloneAllz('tt_en')" /> <em class="fa fa-clone"></em></label>
</th>
<th>Cost</th>
</tr>
<tr>
<td>00067</td>
<td class="cde">
<input type="text" name="prd_cde" id="prd_cde|67" class="form-control" value="3000009" />
</td>
<td class="tt_en">
<input type="text" name="prd_title_en" id="prd_title_en|67" class="form-control" value="TRANSFER" />
</td>
<td>
<input type="number" name="prd_cost" id="prd_cost|67" class="form-control" value="800" />
</td>
</tr>
<tr>
<td>00068</td>
<td class="cde">
<input type="text" name="prd_cde" id="prd_cde|68" class="form-control " value="3000009" />
</td>
<td class="tt_en">
<input type="text" name="prd_title_en" id="prd_title_en|68" class="form-control " value="TRANSFER" />
</td>
<td>
<input type="number" name="prd_cost" id="prd_cost|68" class="form-control" value="600" />
</td>
</tr>
</table>

Javascript multiplication when add row

I have a problem with my code, when I add the javascript multiplication not running, but at first row just fine. I think the problem id must be unique and i change to name, but still not work.
You can try mycode below.
function multiplyBy() {
num1 = document.getElementById("input1").value;
num2 = document.getElementById("input2").value;
document.getElementById("output").value = num1 * num2;
}
$(document).ready(function() {
$("#addCF").click(function() {
$("#customFields").append('<tr><td>1</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control" name="harga_satuan[]" id="input1" onkeyup="calc()" value="" type="text"></td><td><input class="form-control" id="input2" onkeyup="calc()" name="jumlah_beli[]" type="text"></td><td><input class="form-control" name="sub_total[]" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td>
<input class="form-control" name="harga_satuan[]" id="input1" onkeyup="multiplyBy()" value="" type="text">
</td>
<td>
<input class="form-control" id="input2" onkeyup="multiplyBy()" name="jumlah_beli[]" type="text">
</td>
<td>
<input class="form-control" name="sub_total[]" id="output" onkeyup="multiplyBy()" type="text">
</td>
<td>
<button class="remCF"><i class="fa fa-times" style="color:red;"></i></button>
</td>
</tr>
</tbody>
</table>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
You are using same id multiple times and it gives wrong behavior with jquery/javascript. I have added some classes into each text boxes and replaced mutiplyby function with on keyup jquery function.
Try this with your page and see it gives you your desired output.
$(document).on('keyup','.input',function(){
var num1 = $(this).parents('tr:first').find('.input:first').val();
var num2 = $(this).parents('tr:first').find('.input:last').val();
$(this).parents('tr:first').find('.sub-total').val(num1 * num2);
});
$(document).ready(function() {
$("#addCF").click(function() {
$("#customFields").append('<tr><td>1</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control input input1" name="harga_satuan[]" id="input1" onkeyup="multiplyBy(this)" value="" type="text"></td><td><input class="form-control input input2" id="input2" onkeyup="multiplyBy()" name="jumlah_beli[]" type="text"></td><td><input class="form-control sub-total" name="sub_total[]" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td>
<input class="form-control input" name="harga_satuan[]" id="input1" onkeyup="multiplyBy()" value="" type="text">
</td>
<td>
<input class="form-control input" id="input2" onkeyup="multiplyBy()" name="jumlah_beli[]" type="text">
</td>
<td>
<input class="form-control sub-total" name="sub_total[]" id="output" onkeyup="multiplyBy()" type="text">
</td>
<td>
<button class="remCF"><i class="fa fa-times" style="color:red;"></i></button>
</td>
</tr>
</tbody>
</table>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
The values of id attributes must be unique across the whole document. Each time you do the calculation you are adding another element with the id output. The DOM doesn't know which one you mean.
I think the problem id must be unique and i change to name
Yes that's it, the id should be unique in the same document, instead you don't need id's here it will be better to use common classes :
<tr>
<td>
<input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td>
<input class="form-control calculation" name="harga_satuan[]" value="" type="text">
</td>
<td>
<input class="form-control calculation" name="jumlah_beli[]" type="text">
</td>
<td>
<input class="form-control output" name="sub_total[]" id="" type="text">
</td>
<td>
<button class="remCF"><i class="fa fa-times" style="color:red;"></i></button>
</td>
</tr>
NOTE : No need for inline-events better to attach your event in the JS code, Check my suggestion using input event that is more efficient than keyup when you track the user input's.
I've added also an index to enumerate the rows...
Hope this helps.
Working Snippet :
$(document).ready(function() {
var index = 2;
$("#addCF").click(function() {
$("#customFields").append('<tr><td>'+index+'</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control calculation" name="harga_satuan[]" value="" type="text"></td><td><input class="form-control calculation" name="jumlah_beli[]" type="text"></td><td><input class="form-control output" name="sub_total[]" value="" type="text"></td><td><button class="remCF"><i class="fa fa-eye" style="color:red;"></i></button></td></tr>');
index++;
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("table").on('input', '.calc', function(){
var parent_row = $(this).closest('tr');
var num1 = parent_row.find('[name="harga_satuan[]"]').val();
var num2 = parent_row.find('[name="jumlah_beli[]"]').val();
parent_row.find('.output').val(num1*num2);
});
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td><input class="form-control calc" name="harga_satuan[]" value="" type="text"></td>
<td><input class="form-control calc" name="jumlah_beli[]" type="text"></td>
<td><input class="form-control output" name="sub_total[]" id="" type="text"></td>
<td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td>
</tr>
</tbody>
</table>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>

Row count in dynamically generated table using JQuery

I've a table with header and footer and a default row already created. When I add more rows dynamically I don't get the exact row count. It always returns the correct row count if I add them before.
Below is the code I've written -
<table id="empTable" class="table table-responsive table-striped table-bordered">
<thead>`enter code here`
<tr>
<td>Name of Employee</td>
<td>Father's Name/Husband's Name</td>
<td>Basic</td>
<td>Total attendance</td>
<td>Clear</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
<tr>
<td><input id="emp_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input id="father_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
<script>
//function to add/remove rows
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
//function to return value of Dynamic content
function GetDynamicTextBox(value) {
return '<td><input name="DynamicTextBox" type="text" value="" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="text" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>'
}
</script>
And I'm using this line to return row count but it's not working -
var rowCount = document.getElementById("TextBoxContainer").rows.length;
$('#btnSave').on('click', function() {
alert(rowCount);
})
I've tried all the solutions from stackoverflow but not getting why it's not working for dynamic rows whereas same code I saw in a fiddle working.
Please help.
Because you create new rows on the fly you need to move this line:
var rowCount = document.getElementById("TextBoxContainer").rows.length;
inside:
$('#btnSave').on('click', function() {
And as per #charlietf comment I would suggest to change the row count in:
var rowCount = $("#TextBoxContainer tr").length;
//function to return value of Dynamic content
function GetDynamicTextBox(value) {
return '<td><input name="DynamicTextBox" type="text" value="" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="text" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>';
}
$(function () {
$('#btnSave').on('click', function() {
var rowCount = $("#TextBoxContainer tr").length;
console.log('Rows: ' + rowCount);
})
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="empTable" class="table table-responsive table-striped table-bordered">
<thead>`enter code here`
<tr>
<td>Name of Employee</td>
<td>Father's Name/Husband's Name</td>
<td>Basic</td>
<td>Total attendance</td>
<td>Clear</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
<tr>
<td><input id="emp_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input id="father_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button>
<button id="btnSave" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="ASavee controls"><i class="glyphicon glyphicon-plus-sign"></i> Save </button></th>
</tr>
</tfoot>
</table>

Categories

Resources