jQuery function is not working on newly added row - javascript

I want to make simple real time calculator without page refresh with jquery.
I added dynamic table row with jquery and applied some method in the input fields but that is not working perfectly in newly added rows.
newly added rows are only working when I change something in the default rows.
Here is my html codes:
<button type="button" id="addBillingRow" class="btn btn-success btn-sm fa fa-plus fa-3x float-right">add</button>
<table class="table table-bordered" id="dynamic_field_shipping">
<thead>
<tr>
<th width="10%">Date</th>
<th width="20%">Purpose</th>
<th width="20%">Amount</th>
<th width="10%">Quantity</th>
<th width="30%">Total</th>
<th width="10%">#</th>
</tr>
</thead>
<tbody>
<tr class="ship_bill">
<td>
12/12/17
</td>
<td>
<input id="purpose" type="text" name="purpose" required>
</td>
<td>
<input id="amount" name="amount" type="text"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" required>
</td>
<td>
<input id="quantity" name="quantity" required="required" type="number" min="0" value="0">
</td>
<td>
<strong><i><span class="multTotal">0.00</span></i></strong>
</td>
<td>
</td>
</tr>
</tbody>
</table>
<table class="table table-bordered">
<tbody>
<tr>
<td width="50%"><strong><i>Bill Amount:</i></strong></td>
<td><strong><i><span id="grandTotal">0.00</span></i></strong></td>
</tr>
</tbody>
</table>
Here is my jQuery codes:
var i=1;
$('#addBillingRow').click(function(){
i++;
$('#dynamic_field_shipping').append('<tr class="ship_bill" id="row'+i+'"><td></td><td><input id="purpose" type="text" name="purpose" required></td><td><input id="amount" name="amount" type="text" required></td><td><input id="quantity" name="quantity" required="required" type="number" min="0" value="0"></td><td><strong><i><span class="multTotal">0.00</span></i></strong></td><td>X</td></tr>');
});
$(document).on('click', '.btn_remove', function(e){
e.preventDefault();
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
function multInputs() {
var mult = 0;
// for each row:
$("tr.ship_bill").each(function () {
// get the values from this row:
var $amount = $('#amount', this).val();
var $quantity = $('#quantity', this).val();
var $total = ($amount * 1) * ($quantity * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
$(".ship_bill input").change(multInputs);
If you want you can check the live code here:
https://jsfiddle.net/wasid/3xkcLdss/1/
besides I also wanted to use this code in jquery append() for allowing only numbers in input fields. but could not use it either.
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"

Try this
$("tbody").on('change', '.ship_bill input', multInputs);

Related

How to calculate some field in one row using jquery

I have created some code to calculate some fields in row. But i added some function, so i can add row dynamically using jquery.
This is my source code on my codepen
Click here!
this is my function to calculate qtyItem column and price columns
$("tbody").keyup(function() {
var qtyItem = parseFloat($("#qtyItem").val());
var price = parseFloat($("#price").val());
var subTotal = qtyItem * price;
$("#subTotal").attr("value", subTotal);
});
the problem is when i try to calculate the 1st row, it's work fine. but the others not affected by the function in my script.
IDs must be unique, so avoid dulicated. For this you can use Template_literals (see the ${nextIdx} in the snippet).
You need to consider NaN values returned by parseFloat
Now, in your price event handler you can change strategy:
get the parent row
find an element looking for it in the children having an id starting with
The new code is now:
$(".addItem").click(function(e) {
var nextIdx = $("table tbody tr").length + 1;
var row = `<tr>
<td><input type="text" class="form-control" name="itemName" id="itemName${nextIdx}"></td>
<td><input type="number" class="form-control" name="qtyItem" id="qtyItem${nextIdx}"></td>
<td><input type="number" class="form-control" name="price" id="price${nextIdx}"></td>
<td><input type="number" class="form-control" name="subTotal" id="subTotal${nextIdx}" readonly></td>
</tr>`;
$("table").append(row);
});
//subTotal count
$("tbody").keyup(function(e) {
var crow = $(e.target).closest('tr'); // get parent row
// find qtyItem in the children
var qtyItem = parseFloat(crow.find("[id^=qtyItem]").val()) || 0;
// find price in the children
var price = parseFloat(crow.find("[id^=price]").val()) || 0;
var subTotal = qtyItem * price;
crow.find("[id^=subTotal]").attr("value", subTotal);
});
table,td, th{
border: 2px, solid, black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<label for="username">Username</label>
<input id="username" type="text" placeholder="Input your username"> <br>
<label for="date">Date</label>
<input id="date" type="date"> <br>
<label for="itemSold">Item List</label>
<table>
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>price</th>
<th>SubTotal</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="addItem">Add Item</button>
</form>
You can do it without use id attribute, instead that u can use the name attribute for each row.
$(document).ready(function() {
//add row on button click
$(".addItem").click(function() {
var row = `<tr>
<td><input type="text" class="form-control" name="itemName"></td>
<td><input type="number" class="form-control" name="qtyItem"></td>
<td><input type="number" class="form-control" name="price"></td>
<td><input type="number" class="form-control" name="subTotal" readonly></td>
</tr>`;
$("table").append(row);
});
const $tBody = $('tbody')
//subTotal count
$tBody.on("keyup", 'input[type="number"]', function() {
let $parentTr = $(this).closest("tr");
let qtyItem = parseFloat($parentTr.find('td input[name="qtyItem"]').val());
let price = parseFloat($parentTr.find('td input[name="price"]').val());
if (!isNaN(qtyItem) && !isNaN(price)) {
let subTotal = qtyItem * price;
$parentTr.find('td input[name="subTotal"]').attr("value", subTotal);
}
});
});
table,td, th{
border: 2px, solid, black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<label for="username">Username</label>
<input type="text" placeholder="Input your username"> <br>
<label for="date">Date</label>
<input type="date"> <br>
<label for="itemSold">Item List</label>
<table>
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>price</th>
<th>SubTotal</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="addItem">Add Item</button>
</form>

Input element added does not appear on PHP post

I have tried to add input text element to my form
through this jquery code below
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="" name="item'+counter+'"/></td>';
cols += '<td><input type="text" class="" name="rate'+counter+'"/></td>';
cols += '<td><input type="text" class="" name="quantity'+counter+'"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("#myTable").append(newRow);
$("#itemcounter").val(counter);
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
var count = $("#itemcounter").val();
$("#itemcounter").val(count-1);
counter = count -1;
});
});
Now the form is as below:
<form action="{{url('/billgenerate')}}" method="post">
<input type="hidden" name="itemcounter" id="itemcounter" value="">
<table id="myTable" class="table order-list">
<thead>
<tr>
<td>Item Name</td>
<td>Rate</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-4">
<input type="text" name="item0" class="" style="width:22em" />
</td>
<td class="col-sm-3">
<input type="text" name="rate0" class=""/>
</td>
<td class="col-sm-3">
<input type="text" name="quantity0" class=""/>
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block" name="addrow" id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</form>
when I add add new row, it adds successfully, and also the element is added with its name increment by 1 so that while posting the page the name does not get conflicts.
but when I try to add a input predefined inside the table, php recognizes that particular element.
but when I try to add it through jquery code, it does not return the elements which are added. where am i going wrong?

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>

get input values inside a table td

I have table with a button as following; I'm trying to get the values of td's using jQuery.
My table:
<table class="table" id="Tablesample">
<tr>
<th style="display:none;">
#Html.DisplayNameFor(model => model.Id)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="#item.Key" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="#item.Id" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
}
</table>
<button id="btnSave">Save</button>
then I'm trying to get the value using jquery:
$('#btnSave').click(function () {
$('#Tablesample tr').each(function () {
var row = $(this).closest("tr"); // Find the row
var text = row.find(".keyvalue").text(); // Find the text
var keval = text.find("input").text();
alert(keval);
});
});
but I'm not getting any values.
I also tried something like this but it doesn't work either:
$("#Tablesample tr:gt(0)").each(function () {
var this_row = $(this);
var key = $.trim(this_row.find('td:eq(0)').html());
alert(key);
});
The issue is due to your DOM traversal logic. Firstly this is the tr element, so closest('tr') won't find anything. Secondly, you're getting the string value from the text() of .keyvalue, then attempting to find an input element in the text instead of traversing the DOM. Finally, you need to use val() to get the value of an input.
I'd strongly suggest you familiarise yourself with the methods jQuery exposes and how they work: http://api.jquery.com
With all that said, this should work for you:
$('#btnSave').click(function() {
$('#Tablesample tr').each(function() {
var keval = $(this).find(".keyvalue input").val();
console.log(keval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="Tablesample">
<tr>
<th style="display:none;">
Model
</th>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key1" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id1" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key2" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id2" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
<tr>
<td style="display:none;" class="keyvalue">
<input type="text" name="Key" value="Key3" class="form-control" id="configKey" readonly="readonly">
</td>
<td>
<input type="text" name="Key" value="Id3" class="form-control" id="configId" readonly="readonly">
</td>
</tr>
</table>
<button id="btnSave">Save</button>
Note that the first value is undefined as your th element in the first row contains no input element. I'd suggest separating the table using thead/tbody if you want to exclude that row.

On click table td input append same tr every time

I have a problem in JavaScript to repeat a same tr after,when i click the td elements.
My html code bellow:
<table id="tabl2" class="table time-table table-bordered table-striped budrow">
<thead>
<tr>
<th class="cal-head">Rates</th>
<th class="cal-head">Start date</th>
<th class="cal-head">End date</th>
</tr>
</thead>
<tr>
<td>
<input type="number" readonly placeholder="Rates">
</td>
<td>
<input type="text" readonly id="start" placeholder="Start date">
</td>
<td>
<input type="text" class="datepicker" name="enddate" placeholder="End date">
</td>
</tr>
I tried with this js but failed:
$('.budrow').click(function(){
$(this).find('tr').append('<tr> <td></td> <td></td> <td></td> </tr>');
});
Please help me.
Try to use:
var $table = $('#tabl2');
$table.click(function(e){
var $tr = $(e.target).closest('tr');
if (($tr.parent().prop("tagName") != 'THEAD') && $tr.is(":last-child"))
$tr.after($tr.clone());
});
JSFiddle.
Bind the click event to the clicked element, select the current row using closest() and then append the new row using after() function:
$('.btn').on('click', function() {
var that = $(this);
var newRow = '<tr><td colspan="3">This is a new row</td></tr>';
that.closest('tr').after(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<button class="btn">click</button>
</td>
<td>
<button class="btn">click</button>
</td>
<td>
<button class="btn">click</button>
</td>
</tr>
</tbody>
</table>
You can clone and add the new row, also it will be better to use a add button separately
<button class="budrow">Add</button>
<table id="tabl2" class="table time-table table-bordered table-striped budrow">
<thead>
<tr>
<th class="cal-head">Rates</th>
<th class="cal-head">Start date</th>
<th class="cal-head">End date</th>
</tr>
</thead>
<tr>
<td>
<input type="number" readonly placeholder="Rates" />
</td>
<td>
<input type="text" readonly id="start" placeholder="Start date" />
</td>
<td>
<input type="text" class="datepicker" name="enddate" placeholder="End date" />
</td>
</tr>
</table>
then
jQuery(function ($) {
var $tr = $('#tabl2 tbody tr').eq(0);
$('button.budrow').click(function () {
var $clone = $tr.clone();
$('#tabl2').append($clone);
$clone.find('.datepicker').removeClass('hasDatepicker').datepicker();
});
$('.datepicker').datepicker();
});
Demo: Fiddle
$('.budrow tbody input').click(function(e){
makeClone(e);
});
function makeClone(e){
var newClone = $(e.target).closest("tr").clone();
$("#tabl2 tbody").append(newClone);
$(newClone).click(function(ev){
makeClone(ev);
})
}

Categories

Resources