Find sum of automatically generated input fields value - javascript

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.

Related

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.

How to submit the dynamical input field into the database?

I am displaying the input field dynamically which is working for me.
The issue is,
I have to submit the form. I have tried some code as below but it's not working.
I am using Codeigniter.
Controler code
public function register(){
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
$afterxss=$this->security->xss_clean($save);
if ($afterxss)
{
$this->db->insert('tbl_register',$afterxss);
$response['error'] = "true";
$response['msg'] = "Successfully";
}else{
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
echo json_encode($response);
}
I am adding the field dynamically and incrementing the name. Please let me know what name I have to use here
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
Below is the code for adding the input field dynamically.
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
var addrm = '';
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
numberIncr++;
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>');
}
count++;
});
$(document).on('change', '.pp_fileStatus', function(event) {
if (($(this).val() == '1') || ($(this).val() == '3')) {
$(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '" class="form-control commnumber dynamicVal" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '" class="form-control" placeholder="Remark">');
} else {
$(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '" class="form-control dynamicVal" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
}
});
});
$('#register').on('submit', function(event) {
event.preventDefault();
// adding rules for inputs with class 'comment'
$('.dynamicVal').each(function() {
$(this).rules("add", {
required: true
})
});
// test if form is valid
if ($('#register').validate().form()) {
$.ajax({
//url:"process.php",
url: baseUrl + "/Customer_control/register",
type: "POST",
dataType: "json",
data: $('#register').serialize(),
success: function(data) {
alert("success");
},
}); // AJAX Get Jquery statment
}
//alert('hellow');
});
$('#register').validate({
errorPlacement: function(error, element) {
if (element.is("select")) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
<div id="clicktoadd">Add More</div>
<form action="#" method="post" id="register" name="register">
<div class="row">
<div class="medication_info">
</div>
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
Can anyone here to help me out with this issue?
You can use arrays for multiple names in HTML form and then get the values using Foreach Loop in PHP (CodeIgniter).
Here is how you should change your code: Change your this line:
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
To:
$(".medication_info").append('<select name="pp_fileStatus[]" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
Note: I just changed select field name to "pp_fileStatus[]" and remove numberIncr variable
Now you can access this field name values in your controller like this.
$pp_fileStatus = $this->input->post('pp_fileStatus');
Here $pp_fileStatus is an array and contains all the values of pp_fileStatus.
You can do same for your other form fields too.
So you get rid of giving names to fields by incrementing one to a variable.
Hope this solves your problem.
You can update your register function like this:
public function register(){
$insert_array = [];
$pp_fileStatus = $this->input->post('pp_fileStatus');
$reasonDate = $this->input->post('reasonDate');
$reasonAmt = $this->input->post('reasonAmt');
$remark = $this->input->post('remark');
foreach ($pp_fileStatus as $key => $value) {
$insert_array[] = array(
'pp_fileStatus' => $value,
'reasonDate' => $reasonDate[$key],
'reasonAmt' => $reasonAmt[$key],
'remark' => $remark[$key]
);
}
$this->db->insert_batch('tbl_register',$insert_array);
}
Update this function according to your needs
you need to create a function for your submit actions, which you call (make available) on document load and also with your change event, after having appended the DOM.
simplified example:
$(document).ready(function() {
my_submit(); // enables your submit calls
$(document).on('change', '.pp_fileStatus', function(event) {
// your append code
my_submit(); // again, enables your submit calls
})
}
function my_submit(){
$('#register').on('submit', function(event) {
// your code
})
$('#register').validate({
// your code
})
}

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 of amount not working by using ajax response

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);
});

Loop through multiple form and get their input values in jquery

I am dynamically generating forms using jquery. How can I loop through all the forms and alert their input values.
CODE FOR GENERATING FORMS
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
WHERE I TRIED GETTING THE VALUES OF THE INPUT FIELD BY ID
$('#saveAdj').click(function() {
$('form').each(function() {
alert($('.EmpId').val());
});
});
$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
});
});
$('selector', container) will help you to search from container only;
You aren't providing any context for where to find .EmpId.
The callback function passed to the each() method will automatically be passed values for accessing the collection being enumerated. If you use those argument values, you can provide that context by passing it as the second argument to the JQuery object.
$('#saveAdj').click(function() {
// JQuery's .each() method will automatically pass 3 arguments
// to the provided callback function:
// a reference to the index position of that element
// a reference to the element being enumerated at the moment
$('form').each(function(index, element) {
// The element argument can be passed as the second argument to
// the JQuery object (after the selector) to provide context for where to search
alert($('.EmpId', element).val());
});
});

Categories

Resources