sum of amount not working by using ajax response - javascript

I try this format but its not working
**
"name": [{
"id": 3,
"qty": 2
}, {
"id": 4,
"qty": 5
}]
**
This is my function once after get response on keyup qty textbox i want to add all amount in one textbox and show all entered value id and qty in above mention format
function _getPriceCalculation() {
var sum = 0;
$.ajax({
type: "GET",
url: $('#categoryList').val(),
dataType: 'json',
success: function(data) {
$.each(data, function(index, item) {
$('<div id="price_calculation"><div class="col-lg-4 main"><input type="text" value="'+item.name+'" readonly class="form-control"/></div><div class="col-lg-4 main" style="display:none;"><input type="text" name="id" id="price-'+item.id+'" value="'+item.price+'" readonly class="form-control" onkeypress="return isNumber(event)"/></div><div class="col-lg-4 main"><input type="text" value="" name="qty" id="qty-'+item.id+'" class="form-control qty" onkeypress="return isNumber(event)"/></div><div class="col-lg-4 main"><input type="text" name="amount" id="amount-'+item.id+'" value="" readonly class="form-control amount" onkeypress="return isNumber(event)"/></div>').appendTo("#price-calculation-view");
$("#qty-"+item.id).keyup(function(){
var qty = $("#qty-"+item.id).val();
var price = $("#price-"+item.id).val();
var total = qty * price;
$("#amount-"+item.id).val(total);
});
});
}
});
}
$(document).on("keyup", "input[name='qty']", function() {
//$('input[name="qty"]').change(function(){
// alert();
var name = [];
$('.main').each(function(index,item){
var obj={};
obj.id = $(item).find('input[name="id"]').val();
obj.qty = $(item).find('input[name="qty"]').val();
name.push(obj)
});
console.log(name);
});
How to achieve this ?

$("#qty-"+item.id) DOM elements are added dynamically on the page.
You have to use event delegation for elements which were added dynamically.
You should bind keyup event handler using .on() method.
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
$(document).on('keyup','#qty-'+item.id, function(){
var qty = $("#qty-"+item.id).val();
var price = $("#price-"+item.id).val();
var total = qty * price;
$("#amount-"+item.id).val(total);
});

Related

Find sum of automatically generated input fields value

I have a button that when you click it appends an input fields in a div,
this values comes from ajax request.
var i = 0;
$(document).on('click', '#add-btn', function() {
++i;
var user = $('#productName').attr('value');
var price = $('#price').attr('value');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getPrice.php",
data: {user:user, price:price},
dataType: "html", //expect html to be returned
success: function(response){
$("#dynamicAddRemove").append('<tr style="height:5em;" id="tr"><td><input name="productName['+i+']" readonly class="form-control" type="text" value="'+user+'"/></td><td><div class="quantit buttons_added"><input class="form-control quantity" id="number" type="number" name="qty[' + i + ']" value="1"/></div></td><td><input class="form-control amount" type="text" readonly value="'+price+'" name="price[' +i +']"/></td><td class="td"><input type="text" value="'+price+'" name="subTotal['+i+']" placeholder="Subtotal" class="form-control subtotal" id="grandTotal" readonly/><td><button type="button" name="add" class="btn btn-danger remove-tr">-</button></td>');
}
});
});
after appending the input fields now i want to add every value of the subTotal to get grandTotal.
var iSum = 0;
$(document).on('mouseout', '.amount , .quantity, #addvalue', function() {
iSum = 0;
$('input[name="subTotal[]"]').each(function(){
var LiSum =parseInt($('input[name="subTotal[]"]').val());
if(LiSum != undefined || LiSum != ''){
iSum+=LiSum;
}
});
$('#sum').html(iSum);
alert(iSum);
});
after successfully appending values, i keep on getting 0 as grandTotal
Replace $('input[name="subTotal[]"]') by $('input[name^="subTotal"]'). This will find all input fields with names starting with "subTotal". The name "subTotal[]" you were originally looking for does not appear anywhere in your markup.

How To Validate Selected Value From Multiple Select Box Using The Same Attributes (ID or Class)?

How To Validate Selected Value From Multiple Select Box Using The Same Attributes (ID or Class)?.
Hello problem solvers, I'm struggling to develop the best validation scenario for my multiple select drop down options. So, I have a form functionality that able to insert as many as I want dynamic select box where the data is generated from MySQL database whenever the button is clicked.
Please see below GIF animation.
enter image description here
This is my jQuery code to create the add/remove form elements:
$(document).on('click', '#add', function() {
var data = '<tr><td width="40" align="center">'+window.globalCounter+'</td><td width="350"><select data-select="jenis_layanan" name="id_jenis_layanan['+window.globalCounter+']" id="id_jenis_layanan'+window.globalCounter+'" data-id="'+window.globalCounter+'" class="form-control required input-group" data-live-search="true" data-msg-required="Pilih layanan">'+ambil_data_jenis_layanan(window.globalCounter)+'</select></td><td width="70"><input type="text" name="kode_jenis_layanan['+window.globalCounter+']" id="kode_jenis_layanan" data-id="'+window.globalCounter+'" class="form-control input-sm" placeholder="Kode" readonly></td><td width="100"><input type="text" name="tarif_jenis_layanan['+window.globalCounter+']" id="tarif_jenis_layanan" data-id="'+window.globalCounter+'" class="form-control input-sm" placeholder="Tarif" readonly></td><td width="80"><input type="text" name="satuan_jenis_layanan['+window.globalCounter+']" id="satuan_jenis_layanan" data-id="'+window.globalCounter+'" class="form-control input-sm" placeholder="Satuan" readonly></td></td><td width="110"><input data-text="berat_jumlah" type="text" name="berat_jumlah['+window.globalCounter+']" id="berat_jumlah'+window.globalCounter+'" data-id="'+window.globalCounter+'" class="form-control required number input-sm" placeholder="Berat/Jumlah" data-msg-required="Wajib diisi" data-msg-number="Harus angka"></td></td><td width="150"><input type="text" name="subtotal['+window.globalCounter+']" id="subtotal'+window.globalCounter+'" data-id="'+window.globalCounter+'" class="form-control input-sm" placeholder="Subtotal" readonly></td><td width="40" align="center"><button type="button" class="btn btn-danger btn-sm" id="delete"><i class="glyphicon glyphicon-remove"></i></button></td></tr>';
tableForm.find('tbody').append(data);
window.globalCounter++;
});
This is the function to get the types of service from CodeIgniter:
// ambil data jenis layanan = retrieve type of laundry services
function ambil_data_jenis_layanan(cnt = 0) {
$.ajax({
type: 'POST',
url: "<?php echo base_url('CucianMasuk/ambil_data_jenis_layanan');?>",
data: {},
dataType: 'JSON',
cache: false,
success: function(response) {
$('select#id_jenis_layanan'+cnt).html('');
var option = '<option value="">Pilih Jenis Layanan</option>';
for (var i = 0; i < response.length; i++) {
option += '<option value="'+response[i]['id_jenis_layanan']+'">'+response[i]['nama_jenis_layanan']+'</option>';
}
$('select#id_jenis_layanan'+cnt).append(option).selectpicker('refresh');
}
});
}
This is the code to fill the select options with data:
public function ambil_detail_jenis_layanan() {
$sql = $this->m_jenis_layanan->jenis_layanan($this->input->post('id'));
echo json_encode(['kode_jenis_layanan' => $sql['kode_jenis_layanan'], 'tarif_jenis_layanan' => $sql['tarif_jenis_layanan'], 'satuan_jenis_layanan' => $sql['satuan_jenis_layanan']]);
}
This current code to validate the selected value from each dynamic generated select options:
// mengambil data jenis layanan berdasarkan pilihan pelanggan
// https://stackoverflow.com/questions/45803813/jquery-select-box-multiple-option-get-value-and-match-values
$(document).on('change', 'select[data-select=jenis_layanan]', function(){
var dataid = $(this).attr('data-id'),
id = $(this).val(),
arr = [],
jenisLayanan = [];
$.each($('select[data-select=jenis_layanan] option:selected'), function(){
arr.push($(this).val());
jenisLayanan.push($(this).text());
});
var values = $('select[data-select=jenis_layanan]').map(function() {
return this.value;
}).toArray();
var hasDups = !values.every(function(v,i) {
return values.indexOf(v) == i;
});
if(hasDups){
// if found duplicate selected values from
// each select options, display such message
// later on planned to put in Bootstrap Modal
// for more professional look
alert('Sorry mate, this service already listed into the form: ' + jenisLayanan.join(', ') + '\n');
return false;
} else {
// if each selected values are not same from each select elements
// get data via AJAX and put in assigned HTML form elements
// and set the cursor focus to the berat_jumlah input box to let the user enter the weight of the laundry of number of clothes being laundry
$.ajax({
type: 'POST',
url: "<?php echo base_url('CucianMasuk/ambil_detail_jenis_layanan');?>",
data: {id:id},
dataType: 'JSON',
cache: false,
success: function(response) {
tableForm.find('tbody tr td input#kode_jenis_layanan[data-id='+dataid+']').attr('value', response.kode_jenis_layanan);
tableForm.find('tbody tr td input#tarif_jenis_layanan[data-id='+dataid+']').attr('value', response.tarif_jenis_layanan);
tableForm.find('tbody tr td input#satuan_jenis_layanan[data-id='+dataid+']').attr('value', response.satuan_jenis_layanan);
tableForm.find('tbody tr td input#berat_jumlah'+dataid).focus();
}
});
}
});
At last, I need to save all data to the database but got stuck at the select element validation. Many thanks for anyone can help.

jquery: how to update input value using onchange?

I created a discount function for my order page where I have an issue that is , on my order page by default when product quantity is 1 then discounted rate show correctly in Final textbox but when I change the Quantity, like 1 to 2,3,4,5.. then my code not works and the amount show without discount rate.
I try to fix this but I not understand where is mistake and how I fix that.
Below is my code which I am using please help and tell me how I make this correct.
Your help will be really appreciate.
Thank you!
function getTotal(row = null) {
if(row) {
var disc = $('#dis_1').val();//
var dec = (disc/100).toFixed(2); //
var total = Number($("#rate_value_"+row).val()) * Number($("#qty_"+row).val()) * dec;
//total = total.toFixed(2);
var rate = Number($("#rate_value_"+row))-total;
total = total.toFixed(2);
$("#amount_"+row).val(total);
$("#amount_value_"+row).val(total);
subAmount();
} else {
alert('no row !! please refresh the page');
}
}
//**---**/
//*---*//
// get the product information from the server
function getProductData(row_id)
{
var product_id = $("#product_"+row_id).val();
if(product_id == "") {
$("#rate_"+row_id).val("");
$("#rate_value_"+row_id).val("");
$("#qty_"+row_id).val("");
$("#amount_"+row_id).val("");
$("#amount_value_"+row_id).val("");
} else {
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#rate_"+row_id).val(response.price);
$("#rate_value_"+row_id).val(response.price);
$("#dis_"+row_id).val(response.discount);
$("#dis_value_"+row_id).val(response.discount);
$("#qty_"+row_id).val(1);
$("#qty_value_"+row_id).val(1);
//DISCOUNT
var disc = $('#dis_1').val();
var dec = (disc/100).toFixed(2);
var total = Number(response.price) * dec;
var rate = Number(response.price)-total;
total = rate.toFixed(2);
$("#amount_"+row_id).val(total);
$("#amount_value_"+row_id).val(total);
subAmount();
} // /success
}); // /ajax function to fetch the product data
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
<td>
<input type="text" name="rate[]" id="rate_1" class="form-control" autocomplete="off" placeholder="Rate">
</td>
<td>
<input type="text" placeholder="Discount" name="dis[]" id="dis_1" class="form-control" autocomplete="off">
</td>
<td>
<input type="text" placeholder="Total Price" name="amount[]" id="amount_1" class="form-control" autocomplete="off">
</td>
I am using my database to fetch the amount like product real rate, discounts.
In your line of HTML
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
you are always calling getTotal with a value of 1, I think you want to instead get the value of the text box when the getTotal function is called and use that as your row value. In jquery you can get the value of the box by
row = $("#qty").val()

Sum up all text boxes with a particular class name?

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

calculate the product of two input fields in javascript using jQuery

I have an input field that I want to populate with the product of two input fields that appear earlier in the form.
<div class="form-group">
<label for="item_name" class="col-lg-2 control-label">Item:</label>
<div class="col-lg-2">
<input type="text" name="item_name[]" placeholder="Name">
</div>
<div class="col-lg-2">
<input type="text" name="item_qty[]" placeholder="Quantity">
</div>
<div class="col-lg-2">
<input type="text" name="item_price[]" placeholder="Price">
</div>
<div class="col-lg-2">
<input type="text" name="item_total[]" placeholder="Total">
</div>
</div>
These input fields can occur multiple times, so I'm attempting to loop over the item_total[] arrray and attach a listener to the focus event.
$.each($("[name='item_total[]']"), function( index, value ) {
$(this).focus(function() {
var value = ?
//not sure how to select the value of the two previous input fields
// var value = $("item_qty[index]") * $("item_price[index]");
console.log(value);
});
});
You can do like this
$('input[name="item_qty[]"],input[name="item_price[]"]').on("change",function (){
var $container = $(this).closest('.form-group');
qty = Number($('input[name="item_qty[]"]',$container).val())||0,
price = Number($('input[name="item_price[]"]',$container).val())||0;
$('input[name="item_total[]"]',$container).val(qty * price);
})
Another solution starts with selector:
$('input[name^="item_qty"],input[name^="item_price"]').on("change",function (){
var $container = $(this).closest('.form-group');
qty = Number($('input[name^="item_qty"]',$container).val())||0,
price = Number($('input[name^="item_price"]',$container).val())||0;
$('input[name^="item_total"]',$container).val(qty * price);
})
Following assumes that you have [] in input names due to repeating rows and will isolate values within repeated row instances
You can traverse to the nearest wrapping container which would be form-group using closest(), then look within that container using find()
I think what you want is to apply change handler to the user inputs and calculate total when they change
$("input[name=item_qty\\[\\]], input[name=item_price\\[\\]]").change(function(){
var $container = $(this).closest('.form-group');
var qty = $container.find('[name=item_qty\\[\\]]') || 0;
var price = $container.find('[name=item_price\\[\\]]') || 0;
$container.find('[name=item_total\\[\\]]').val( qty * price );
});
jQuery requires escaping special characters in selectors which is why there are so many \\ above.
See escaping rules in selectors API Docs
Something like the following would work.
var quantityEl = $('input[name="item_qty[]"]'),
priceEl = $('input[name="item_price[]"]'),
totalEl = $('input[name="item_total[]"]')
;
var calculateTotal = function() {
var quantity = +quantityEl.val().trim(),
price = +priceEl.val().trim(),
total = quantity * price
;
if (!isNaN(total)) {
totalEl.val(total);
}
};
priceEl.on('change keyup paste', calculateTotal);
quantityEl.on('change keyup paste', calculateTotal);
You can do soemthing like this
input1 = $(this).closest($("[name='item_price']")).val()
Or like this
input1 = $("[name='item_price']")[index]).val()

Categories

Resources