jQuery blur event fires multiple times when two inputs involved - javascript

I have dynamically created table with <tr> <td> <inputs>, problem is, when I click first <td> input and I click on to the next td input, jquery blur event fires multiple times. Even after using event.stopImmediatePropagation() and event.preventDefault(), I couldn't able to prevent the multiple firing on blur event and also I used flag set to false to prevent the firing, but I couldn't.
Is there any other way to solve this problem?
for(var i=0;i< data.supplierdetails.length;i++){
var j = (Math.floor(Math.random() * 100000000) + 100000000).toString().substring(1);
supplierdetailshtml += '<tr data-id="'+j+'">';
var description = data.supplierdetails[i].description;
supplierdetailshtml+= '<td><input type="text" name="rawproductname[]" id="rawproductname" value ="'+description+'" class="form-control rawproductname" readonly="true"/></td>';
supplierdetailshtml+= '<td><input type="text" name="hsncode[]" id="hsncode" class="form-control hsncode"/></td>';
var quantity = data.supplierdetails[i].quantity;
supplierdetailshtml+= '<td><input type="text" name="rawproductquantity[]" id="rawproductquantity_'+j+'" value ="'+quantity+'" class="form-control rawproductquantity" readonly="true"/></td>';
var unitcode = data.supplierdetails[i].unitcode;
supplierdetailshtml+= '<td><input type="text" name="rawproductunitcode[]" id="rawproductunitcode" value ="'+unitcode+'" class="form-control rawproductunitcode" readonly="true"/></td>';
supplierdetailshtml+='<td><input type="text" name="rawproductrate[]" id="rawproductrate_'+j+'" value="0.00" class="form-control rawproductrate"/></td>';
supplierdetailshtml+='<td><input type="text" name="rawproductprice[]" id="rawproductprice_'+j+'" value="0.00" class="form-control rawproductprice"/></td>';
supplierdetailshtml+= '<td><input type="text" name="rawproductgst[]" id="rawproductgst_'+j+'" value="0.00" class="form-control rawproductgst"/></td></tr>';
}
$(document).on('blur','.rawproductrate',function(event){
debugger;
var tr_id = $(this).closest('tr').data('id');
//alert("Data ID"+tr_id);
var rawproductquantity = $("#rawproductquantity_"+tr_id).val();
//alert("Raw Product Quantity"+rawproductquantity);
var rawproductrate = $("#rawproductrate_"+tr_id).val();
//alert("Raw Product rate"+rawproductrate);
if (rawproductrate==0 || rawproductrate=="") {
alert("Raw Product Rate Cannot be Zero");
}
var rawproductprice = parseFloat(rawproductrate*rawproductquantity).toFixed(2);
if(isNaN(rawproductprice) || rawproductprice==""){
var rawproductprice_decimal = parseFloat(rawproductprice || 0).toFixed(2);
$("#rawproductprice_"+tr_id).val(rawproductprice_decimal);
}
$("#rawproductprice_"+tr_id).val(rawproductprice);
$('.rawproductrate').off('blur');
event.stopImmediatePropagation();
event.preventDefault();
return false;
});

Related

How to calculate sum of multiple dynamic input fields in Javascript?

I'm trying to calculate sum of multiple dynamic input fields via javascript.
This is my main input:
<input type="text" name="price[]" id="price" value="" class="form-control" />
This is how I'm adding inputs:
$('.btn-add-srvice').on('click', function(e){
e.preventDefault();
var template = '<input type="text" name="price[]" id="price" class="form-control" />';
$(this).before(template);
});
After this, I have a custom function which calculate data from inputs:
function sum() {
var price = document.getElementById('price').value;
var subtotal;
}
It is calculating only one input(not the added inputs). Now, I want to calculate sum of the price of each inputs value that are showing after creating with above function.
Expected result:
input1 = 30
input2 = 30
...... = ...
subtotal = ...
So, the subtotal variable should be filled with sum of for each inputs.
Thank you.
Updated
Now, how could I calculate sum of each row and also subtotal. Below the functions you can find the expected result image link.
My full javascript function:
$(document).on('keyup keydown change', ".price, .months, #mwst, #rabatt",function () {
var months = document.getElementById('months').value;
var mwst = document.getElementById('mwst').value;
var rabatt = document.getElementById('rabatt').value;
var priceSum = 0;
var monthsSum = 0;
$('.price').each(function(){
priceSum += parseFloat(this.value);
});
$('.months').each(function(){
monthsSum += parseFloat(this.value);
});
var subtotal = priceSum * monthsSum;
var sum = priceSum * months;
var mwstValue = subtotal + 7.7 / 100 * subtotal - subtotal;
document.getElementById('subtotal').value = subtotal.toFixed(2);
document.getElementById('sum').value = subtotal.toFixed(2);
document.getElementById('mwst').value = mwstValue.toFixed(2);
var percentage = (mwst / 100) * subtotal;
var result = subtotal + mwstValue - parseFloat(rabatt);
document.getElementById('total').value = result;
});
My full dynamic inserted inputs:
$('.btn-add-srvice').on('click', function(e){
e.preventDefault();
var template =
'<div class="col-md-12" style="padding:0">'+
'<div class="col-md-6" style="padding-left:0px">'+
'<div class="form-group">'+
'<select style="width: 100%" id="service_id" name="service_id[]" class="service_id ">'+
'#foreach($servicesList as $sli)'+
'<option value="{{$sli->id}}">{{$sli->name}}</option>'+
'#endforeach'+
'</select>'+
'</div>'+
'</div>'+
'<div class="col-md-3" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="price[]" id="price" value="" class="form-control price" />'+
'</div>'+
'</div>'+
'<div class="col-md-1" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="months[]" id="months" value="" class="form-control months" />'+
'</div>'+
'</div>'+
'<div class="col-md-2" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="sum[]" id="sum" value="" class="form-control sum" />'+
'</div>'+
'</div>'+
'<div>'+
/*'<button type="button" class="btn btn-default btn-xs remove">Remove</button>'+*/
'</div>'+
'</div>';
enter code here
$(this).before(template);
});
Here is the link how is looking now and the expected result:
https://ibb.co/sVv3qGF
You are giving same id to multiple elements. Give class instead. Then get their sum.
var sum = 0;
$('.price').each(function(){
sum += parseFloat(this.value);
});
Try like this. use class in HTML elements and in jquery try to loop and get the value and sum it.
$('.btn-add-srvice').on('click', function(e){
e.preventDefault();
var template = '<input type="text" name="price[]" id="price" class="form-control price" />';
$(this).before(template);
});
$(document).on('keyup', ".price",function () {
var total = 0;
$('.price').each(function(){
total += parseFloat($(this).val());
})
console.log(total)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="price[]" id="price" value="" class="form-control price" />
<input type ="button" value="add" class="btn-add-srvice"/>
First, your template string for adding inputs is wrong, an ID is, as the name implies, a unique identifier and can only be used once on a page. You don't need id so remove it from the template
var template = '<input type="text" name="price[]" class="form-control" />':
Now just update the input sum function:
function sum() {
var priceElements = document.querySelectorAll('[name^=price]');
var sum = 0;
priceElements.forEach(function(element) {
sum = sum + element.value;
});
console.log(sum);
}
At the time of adding dynamic input field, you should give unique id
for each field.
Then Maintain the list of unique ids.
Iterate on that list and calculate the sum.
let subtotal;
const summOfValues = (summ, element) => summ + Number(element.value);
$('.btn-add-srvice').on('input', function(){
subtotal = $('[name="price[]"]',this).toArray().reduce(summOfValues);
$('other').val(subtotal);
})
Give each input a common class. Give, the below give code a try.
function doSum() {
var x_names = document.getElementsByClassName("x_name")
for(var i = 0; i < x_names.length; i++) {
alert(x_names[i].value)
// You can do sum of values here
}
}
<input type="text" class="some_name" name="price[]" id="price" value="">
<input type="text" class="some_name" name="somethingElse" id="somethingElse" value="">

dynamically add input field value jQuery

html code we can get the value
<input type="text" name="value1[]" id="value1"/>
<input type="mail" name="value2[]" id="value2"/>
<input type="text" name="total[]" id="total" />
i can try with this in jQuery i can get only html value result, after add new row i can't get the value
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item1</td>';
cols += '<td><input type="text" class="form-control" name="value1[]" id="value2' + counter + '"></td>';
cols += '<td><input type="text" class="form-control" name="foreign_milion[]" id="foreign_milion_' + counter + '"></td>';
cols += '<td><input type="text" readonly class="form-control" name="total_milion[]" id="total_"' + counter + '"></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("#value2").keyup(function () {
var value1 = $("#value1").val();
var value2 = $("#value2").val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
$("#total").val(totalincome);
})
});
First of all the id must be unique in the same document, else you'll end up with incorrect HTML code, so you need to replace the ids with common classes instead in your code as a first step.
Then you need to use event delegation to attach the event to your inputs since the must of them are created dynamically with the JS code.
I prefer the use of input event instead of keyup when you track the user inputs, so the event will be something like:
$(document).ready(function() {
var counter = 1;
$("body").on("input", ".calculated_value", function() {
var parent_row = $(this).closest('tr');
var totalincome = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find(".total").val(totalincome);
});
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item ' + counter + '</td>';
cols += '<td><input type="text" class="form-control calculated_value" name="value1[]"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>';
cols += '<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="order-list">
<tr>
<td>Item </td>
<td><input type="text" class="form-control calculated_value" name="value1[]"></td>
<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>
<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>
</tr>
</table>
<button id="addrow">Add row</button>
I have tried this one, may be this is what you are looking into.
please take a look at the snippet.
jQuery(document).ready(function () {
var count = 1;
jQuery('#add').on('click', function(){
var el = `<section id="inpFields">
<input type="text" name="value1[]" id="value`+count+`" placeholder="value `+count+`"/>
<input type="text" name="value2[]" id="value2`+count+`" placeholder="value `+count+`"/>
<input type="text" name="total[]" id="total`+count+`" placeholder="total" />
<button class="totalBtn" data-id="`+count+`">Total</button>
</section>`;
jQuery('#inpFields').append(el);
count++;
});
jQuery('#add').click();
jQuery(document).on('click', '.totalBtn', function(){
var i = this.dataset.id;
var value1 = jQuery('#value'+i).val();
var value2 = jQuery('#value2'+i).val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
jQuery('#total'+i).val(totalincome);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="add">Add Fields</button>
<section id="inpFields">
</section>

Filling a an input based on another

I'm trying to get the price of a product in one field when the name of the product is selected in another field for a simple POS. It works well for the first time but when I add another table row for next product, I don't get the price. Pls help
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_1" class="form-control itemNo" contenteditable="true"></td>
<td><input type="text" data-type="productName" name="itemName[]" id="itemName_1" class="form-control search_canteen_prod chk_product for_Price" autocomplete="off"></td>
<td><input type="number" name="price[]" id="price_1" readonly class="form-control changesNo price for_Price New_price" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" name="quantity[]" id="quantity_1" class="form-control changesNo quantity" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="text" name="total[]" readonly id="total_1" class="form-control totalLinePrice totalPrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
</tr>
</tbody>
Adding another row dynamically
var i=$('table tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type= data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt itemNo" contenteditable="true"></td>';
html += '<td><input type="text" data-type="productName" name="itemName[]" id="itemName_'+i+'" class="form-control search_canteen_prod chk_product for_Price" autocomplete="off"></td>';
html += '<td><input type="number" name="price[]" id="price_'+i+'" class="form-control changesNo price New_price for_Price" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" readonly></td>';
html += '<td><input type="text" name="quantity[]" id="quantity_'+i+'" class="form-control changesNo quantity" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="total[]" id="total_'+i+'" class="form-control totalLinePrice totalPrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" readonly></td>';
html += '</tr> <script>$( ".search_canteen_prod" ).autocomplete({source: "canteen/search_for_product.php"});</script>';
$('table').append(html);
i++;
});
Getting the price based on the autocomplete select
//get product prices
$('.chk_product').on('change, keyup, blur', function() {
iid_arr = $('.chk_product').attr('id');
iid = iid_arr.split("_");
var prodd_name = $('.chk_product').val();
$.ajax({
url:"canteen/select_for_canteen_sales.php",
method: "POST",
data:{prodd_name: prodd_name},
dataType: "JSON",
success:function(data)
{
$('#price_'+iid[1]).val(data.selling_price);
} }); });
fetching the price for
if(isset($_POST["prodd_name"]))
{
$prod_nm = $_POST["prodd_name"];
$query_product = "SELECT * FROM canteen_product WHERE product_name = '". $prod_nm."' AND qty > 0 ORDER BY stock_date DESC";
$result_product = mysqli_query($cnn, $query_product);
while($rrow = mysqli_fetch_array($result_product))
{
$data["selling_price"] = $rrow["selling_prce"];
}
echo json_encode($data);
}
Firstly:
If you use table length only after you add the next table row to generate i, it will be 1 for the very next table row you add... becaue you already have one row (with the html ids being like itemNo_1 etc).
Which means that your next-added row will also have the ids ending in 1.
To fix this, you should use i + 1 in your .addmore function to the html-ids of any new table rows. so they start at eg itemNo_2 adn then go up from there.
Secondly:
you can fetch values relative to the current object (accessed using $(this)) - you don't need to fetch them by id.
eg instead of:
$('.chk_product').on('change, keyup, blur', function() {
iid_arr = $('.chk_product').attr('id');
iid = iid_arr.split("_");
var prodd_name = $('.chk_product').val();
try something like:
$('.chk_product').on('change, keyup, blur', function() {
var prodd_name = $(this).val();
for the price - you can likewise do relative tree-traversal... eg if the price is always "up one to the td, then down to the price" you can do something like:
// chk_product-> td -> down to price value
var price = $(this).parent().find(".price").val();
Note: you will need to bug-test this and I recommend looking up the docs for how it works.

How to get the product of two field into another field in each button click

I have 3 textboxes.product of two textboxes are get into another textbox automatically.the fields are quantity and per/unit.then these two is multiplied into the field amount in each click.But the problm is i got the product in first click only..
js
var new_string='<div class="form-group" id="exp_'+unqid+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="quantity_'+unqid+'" type="text" id="quantity" style="margin-right:20px;" class="form-con" placeholder="Quantity" required>'
+'<input name="perunit_'+unqid+'" type="text" id="perunit" style="margin-right:20px;" onchange="getTotalAmount('+unqid+')" class="form-con" placeholder="Per/unit" required>'
+'<input name="amount_'+unqid+'" type="text" id="amount" class="form-con" placeholder="Amount" required></div>';
$("#create").append(new_string);
called function
function getTotalAmount(unqid)
{
alert(unqid);
var q = document.getElementById("quantity").value;
//alert(q);
var p = document.getElementById("perunit").value;
// alert(p);
if(q!='' && p!='')
{
var total = p * q;
// alert(total);
document.getElementById("amount").value = total;
}
}
You can do something like this :
html code
Value 1<input type="text" id="t1"><br/>
Value 2<input type="text" id="t2"><br/>
Result<input type="text" id="t3">
js:
$('#t2').blur(function(){
var a = $('#t1').val();
var b = $('#t2').val();
var c = a*b;
$('#t3').val(c)
});
and check at https://jsfiddle.net/ejzn66n5/

Add and remove inputs dynamicly with a other input

I searched a lot for this, but I can only find +1 -1 solutions.
But I want to set the number of inputs with a other input like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
When the user now writes 5 in the first field, the form should look like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
<input type="text" size="30" maxlength="30" id="input_2" name="input_2">
<input type="text" size="30" maxlength="30" id="input_3" name="input_3">
<input type="text" size="30" maxlength="30" id="input_4" name="input_4">
<input type="text" size="30" maxlength="30" id="input_5" name="input_5">
How can I make this? MUST I use js?
Here's a simple javascript snippet that doesn't make use of any frameworks:
function addInputs() {
var count = parseInt(document.getElementById("count").value);
for (var i = 2; i <= count; i++) {
document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />';
}
}
In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery
This is not the best example but it works and it's a starting point
JS:
$(function(){
$('#master').on('change', function() {
var count = $(this).val();
$('#otherInputs').html('')
for( var i = 0; i < count; i++) {
$('#otherInputs').append(
$('<input>', {type: 'text'})
);
}
});
});
HTML:
<input type="number" id="master" value="1">
<div id="otherInputs"></div>
Demo
In English this is saying...
When you change #master I will empty #master (html('')) loop through and append a new input depending on #master's value
Here's the FIDDLE. Hope it helps. :)
html
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
<div id="container"></div>
script
$('#count').on('keyup', function () {
var $this = $(this);
var count = $this.val();
$('#container').empty();
for (var x = 1; x <= count; x++) {
var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">';
$('#container').append(newInput);
}
});
This worked for me
function AddField() {
var count = $("#countetfield").val();
var i = 1;
var id = $("#container .testClass:last").attr('name');
var test = id.split("_");
id_name = test[1];
while (i <= count) {
id_name++;
var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>';
$("#container").append(a);
i++;
}
}
<input type="text" id="countetfield" value="1" />
<input type="button" value="Go" onclick="AddField();" />
<div id="container">
<input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" />
</div>

Categories

Resources