Add Multiple Levels of Input Fields - javascript

I have a product page that will input a cost, quantity and spit out the cost after taking the product of the 2.
I have figured it out here http://jsfiddle.net/61tch8md/ for the most part (I believe) but the issue I have is that the user can add multiple lines and each line needs to only add the quantity and cost of the fields on that row. Right now when I add additional rows, the first line will control the price for all the lines.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description 1" name="product-1-description" /></td>
<td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity 1" name="product-1-quantity" /></td>
<td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price 1" name="product-1-price"/></td>
<td><span class="wei-price-total"></span></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
JavaScript / Jquery
jQuery( "tr" )
.keyup(function() {
var value = jQuery( ".unit-price" ).val();
var value2 = jQuery( ".quantity" ).val();
var total = value * value2;
jQuery( ".wei-price-total" ).text( total );
})
.keyup()
var counter = 2;
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description" name="product-' +
counter + '-description" /></td><td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity" name="product-' +
counter + '-quantity" /></td><td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price" name="product-' +
counter + '-price"/></td><td><span class="wei-price-total">$49.99</span></td><td>remove</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
jQuery(this).parents('tr').remove();
});
Thanks in advance.

Change your code so it selects the inputs in the row that the keyup happened on.
jQuery('table.order-details').on("keyup", "tr", function() {
var row = jQuery(this);
var value = jQuery( ".unit-price", row ).val();
var value2 = jQuery( ".quantity", row ).val();
var total = value * value2;
jQuery( ".wei-price-total", row ).text( total );
});

Related

Numbers Concatenate instead of Adding

I know that + is used for both addition and concatenation, it depends on what the variable type is. I have tried using Number() and parseFloat(), but I can't seem to get them to work. Here is my code:
var grandtotal;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = row.find('input[id^="TotalPrice"]').val();
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
This code gives me an output like this:
NaN1081083936354412531.5105
However, if I add Number() or parseFloat() to the totalprice line like this:
grandtotal += Number(totalprice);
OR
grandtotal += parseFloat(totalprice);
I get nothing returned.
Anybody have any idea what I need to change? Thank you.
EDIT: I have changed the controller code to this:
var grandtotal = 0;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
Here is the HTML in question:
<td>
<div class="input-group"> <div class="input-group-addon">$ </div>
<input readonly="readonly" readonly id="TotalPrice{{ $loop->iteration }}" name="TotalPrice[]" placeholder="" class="form-control input-md" step="0.01" type="number" value="{{ $item->TotalPrice }}">
</div>
</td>
I am still getting a blank output.
Making grandtotal to 0 with parseFloat() will solve your problem. You are trying to add tr values to undefined variable.
// give grand total a value
var grandtotal = 0;
$(document).ready(function(){
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>
<input type="text" id="TotalPrice" value="1000.50"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="2000"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="10"/>
</td>
</tr>
</table>
<div class="total_price"></div>
Try checking isNaN:
// Inside each
if (totalprice && totalprice.length > 0 && !isNaN(totalprice)) {
grandtotal += parseFloat(totalprice);
}
function getFloat(val) {
if (val && val.length > 0 && !isNaN(val)) {
return parseFloat(val);
}
return null;
}
console.log("getFloat($('#inp1').val()): " + getFloat($('#inp1').val()));
console.log("getFloat($('#inp2').val()): " + getFloat($('#inp2').val()));
console.log("getFloat($('#inp3').val()): " + getFloat($('#inp3').val()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inp1" type="text" value="" />
<input id="inp2" type="text" value="literal" />
<input id="inp3" type="text" value="100" />

How to calculate the final amount on keyup

I am using Codeignator, I am calculating the final amount. If any user enters the total amount that will calculate it and display in the final amount field.
I am adding the input field dynamically as well. I tried some code but it's not working.
I need to calculate using AJAX.
What I am trying to achieve is, This is my first page.
Now if any user enters the total amount something like this then it will display in the final amount field.
If the user wants to add more field the should click on add button and add the price and it will calculate it and display in the field box, I added in the 50.
same as on this.
Would you help me out in this?
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".row_set"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var baseUrl = "http://localhost/test/";
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="row_set custom_fields"><input type="text" name="single_price[]" id="single_p_price' + x + '" placeholder="single price"> <input type="text" name="total_p_price[]" id="total_p_price' + x + '" placeholder="total amount"><div class="btn_row remove_field"> <span> - </span> Remove </div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
//$(this).parent('custom_fields').remove();
$(this).closest('.custom_fields').remove();
x--;
})
/*comment start here $(".medication_info").on('keyup', 'input[id^=total_p_price]', function() {
var that = $(this); // CHANGE HERE
var total_p_price = that.val();
$.ajax({
type: "POST",
url: baseUrl + "/Access_control/calculate_amt",
data: {
total_p_price: total_p_price
},
cache: false,
success: function(html) {
console.log(html);
var single_price = $('#final_amt').val(html);
}
});
});comment end here*/
$('.medication_info').on('keyup', 'input[id^=total_p_price]', function() {
var totalSum = 0;
$('input[id^=total_p_price]').each(function() {
var inputVal = $(this).val();
if ($.isNumeric(inputVal)) {
totalSum += parseFloat(inputVal);
}
});
$('#final_amt').val(totalSum);
});
});
<form>
<div class="medication_info">
<div class="row_set">
<input type="text" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="text" name="total_p_price[]" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total">
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Controller
public function calculate_amt()
{
$total_p_price=$this->input->post('total_p_price');
foreach ($total_p_price as $key => $value) {
$final_amt +=$value;
}
echo $final_amt;
}
Both jQuery and using AJAX to involve a server seems overkill for this operation.
//Find elements in HTML
var singleProductPriceInput = document.getElementById("single_p_price");
var totalProductAmountInput = document.getElementById("total_p_price");
var finalTotalInput = document.getElementById("final_amt");
var button = document.getElementById("submitter");
//Update function
function updatePrice() {
var singleProductPrice = parseFloat(singleProductPriceInput.value);
var totalProductAmount = parseFloat(totalProductAmountInput.value);
var result = (singleProductPrice * totalProductAmount);
if (!isNaN(result)) {
finalTotalInput.value = result.toFixed(2);
}
}
//Submit function
function submit() {
alert("Do your server stuff\nAJAX here");
}
//Bind event listeners
singleProductPriceInput.addEventListener("change", updatePrice);
singleProductPriceInput.addEventListener("keyup", updatePrice);
singleProductPriceInput.addEventListener("mouseup", updatePrice);
totalProductAmountInput.addEventListener("change", updatePrice);
totalProductAmountInput.addEventListener("keyup", updatePrice);
totalProductAmountInput.addEventListener("mouseup", updatePrice);
button.addEventListener("click", submit);
<form>
<div class="medication_info">
<div class="row_set">
<input type="number" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="number" name="total_p_price[]" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total" readonly>
</div>
<input id="submitter" type="button" name="send" value="submit">
</form>
simple Javascript KeyUp Event calculation
$("input").keyup(function () {
var pr = $(this).data("price");
var name = $(this).data("name");
var qut = $(this).val();
var total = pr * qut;
$("#"+name).text(total);
});
$("#placeorder").click(function () {
var total = 0;
$('.t').each(function () {
total += Number($(this).text());
});
$('#total').text(total);
});
.t{
border:0px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Bone Burger:</td>
<td><input type="text" data-name="gold" data-price="28" size="1" /></td>
<td> * 28r.s<td>
<td>= <label id="gold" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Smoke Burger:</td>
<td><input type="text" data-name="sakti" data-price="29" size="1" /></td>
<td> * 29r.s<td>
<td>= <label id="sakti" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Voodoo Burger:</td>
<td><input type="text" data-name="taja" data-price="30" size="1" /></td>
<td> * 30r.s<td>
<td>= <label id="taja" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Ayhuaska Sour:</td>
<td><input type="text" data-name="gay" data-price="18" size="1" /></td>
<td> * 18r.s<td>
<td>= <label id="gay" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>Beyond the Pale:</td>
<td><input type="text" data-name="chhash" data-price="10" size="1" /></td>
<td> * 10r.s<td>
<td>= <label id="chhash" class="t" readonly ></label>r.s</td>
</tr>
<tr>
<td>
<button id="placeorder">Place order</button>
</td>
</tr>
<tr>
<td><p>Total:<span id="total"></span></p></td>
</tr>
</table>
This might be what you want
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".row_set"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var baseUrl = "http://localhost/test/";
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="row_set custom_fields"><input type="text" name="single_price[]" id="single_p_price' + x + '" placeholder="single price"> <input type="text" name="total_p_price[]" class="total_p_price" id="total_p_price' + x + '" placeholder="total amount"><div class="btn_row remove_field"> <span> - </span> Remove </div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
//$(this).parent('custom_fields').remove();
$(this).closest('.custom_fields').remove();
x--;
})
$(".medication_info").on('keyup', 'input[id^=total_p_price]', function() {
// Sum all the values in the total_p_price fields
var that = $(this);
$.ajax({
type: "POST",
url: baseUrl + "/Access_control/calculate_amt",
data: {
total_p_price: $(".medication_info .total_p_price").serialize()
},
cache: false,
success: function(html) {
console.log(html);
var single_price = $('#final_amt').val(html);
}
});
});
});
<form>
<div class="medication_info">
<div class="row_set">
<input type="text" name="single_price[]" id="single_p_price" placeholder="single price">
<input type="text" name="total_p_price[]" class="total_p_price" id="total_p_price" placeholder="total amount">
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
<input type="text" name="final_amt" id="final_amt" placeholder="Final total">
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Trigger change issue in jQuery

I have a table where I have multiple rows, one of the columns being an input for the charge. The html is below:
<tbody>
#foreach($shipment_details as $sd)
<tr style="height:40px" tr id="row{{$sd->id}}">
<td style="width:8%;text-align:center;">
<input type="text" id="piecesNumber" class="form-control" placeholder="No. Pieces" required name="shipment_details[{{$sd->id}}][piecesNumber]" value="{{$sd->pieces_number}}">
</td>
<td style="width:16%;text-align:center;">
<select id="pieces_type" class="form-control full-width" required name="shipment_details[{{$sd->id}}][piecesType]">
#foreach($cPiecetypes as $cPt)
<option value="{{$cPt->id}}"
#if ($sd->pieces_type == $cPt->id) selected="selected"
#endif>{{$cPt->label}}</option>
#endforeach
</select>
</td>
<td>
<select id="pieces_type" class="form-control full-width" required name="shipment_details[{{$sd->id}}][rateType]">
#foreach($cRatetypes as $cRt)
<option value="{{$cRt->id}}"
#if ($sd->rate_type == $cRt->id) selected="selected"
#endif>{{$cRt->label}}</option>
#endforeach
</select>
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="weight" class="form-control" placeholder="Weight" required name="shipment_details[{{$sd->id}}][weight]" value="{{$sd->weight}}">
</td>
<td style="width:16.5%;text-align:center;">
<select id="hazmat" class="form-control full-width" required name="shipment_details[{{$sd->id}}][hazmat]">
<option value="0"
#if ($sd->hazmat = 0) selected="selected"
#endif>No</option>
<option value="1"
#if ($sd->hazmat = 1) selected="selected"
#endif>Yes</option>
</select>
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="description" class="form-control" placeholder="Description" required name="shipment_details[{{$sd->id}}][description]" value="{{$sd->description}}">
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="charge" class="form-control charges" placeholder="Charge" required name="shipment_details[{{$sd->id}}][charge]" value="{{$sd->charge}}">
</td>
<td><button type="button" name="removeExisting" id="{{$sd->id}}" class="btn btn-danger btn_removeExisting">X</button></td>
</tr>
#endforeach
</tbody>
As you see, there is a button at the end of reach row with the class of "btn_removeExisting" which connects to this script:
$(document).on('click', '.btn_removeExisting', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
$( '.charges' ).trigger( 'change' );
alert('removeExisting');
});
The alert is only there to notify me that the script has completed correctly, which is where my problem is. By pressing the button, it correctly deletes the correct row, and alerts me, but the trigger in the middle is where my problem originates.
The script regarding my change of charge trigger:
$(document).on('change', '.charges', function() {
var sum = 0.00;
$('.charges').each(function(){
sum += +$(this).val();
});
$('input[name^="freightBillSubtotal"]').val(sum.toFixed(2));
calcTotal();
});
Now what's odd is if I just change a charge input, the code works, so if I change the charge on one line from 10.00 to 0.00, the subtotal subtracts 10.00. But for some reason it won't do the same for when an entire row (and it's specific charge) is deleted.
Instead of trying to trigger events manually like that, it is better to make a function and call it from both events:
$(document).on('click', '.btn_removeExisting', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
calcSum();
alert('removeExisting');
});
$(document).on('change', '.charges', calcSum);
function calcSum() {
var sum = 0.00;
$('.charges').each(function() {
sum += $(this).val();
});
$('input[name^="freightBillSubtotal"]').val(sum.toFixed(2));
calcTotal();
});
Note: I assumed there was a harmless typo on your line:
sum += +$(this).val();
so I changed it to:
sum += $(this).val();

jQuery double .each looping, help me solve logical issue

I need to solve some calculations and I'm using an .each() loop. I'm populating rows <tr> dynamically so I use .each() to loop through the table but I can't get different values when I have to sort them by vat value.
function callSum(id) {
var counter = 1;
var sum = document.getElementById("sum" + id).value;
var vat = document.getElementById("vat" + id).value;
$('.sumall').each(function() {
$('.vatall').each(function() {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
} else { //if value of VAT is > 0 sum it to vatTotal
document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control"/>
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control "/>
</td>
</tr>
<br><br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control "/>
<br><br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control "/>
Please see disrciptive comments in the source code.
function callSum(id) {
var counter = 1,
sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
//document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotalZero").val( sumallVal )
} else { //if value of VAT is > 0 sum it to vatTotal
//document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotal").val( sumallVal )
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" onchange="callSum(1)" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
Here we go with an enhanced version.
In this version I removed unused stuff, set an appropriate event handler and shortened the syntax slightly
function callSum(id) {
var sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
/* set the value */
$( $(this).val() == 0 ? "#vatTotalZero" : "#vatTotal" ).val( sumallVal )
});
});
}
$(document).ready(function() {
$('.sumall.form-control').on('input', function() {
// get number id directly from string id by deleting all non numbers
callSum( this.id.replace(/[^0-9]/gi, '') );
})
});
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript sums total with addrow

First of all, sorry for my bad english language.
So, I want to sums my 2 coloumn, but i have add.row condition.
Here my code :
<script>
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input type="text" class="form-control qty" name="p_qty[]" /></td>
<td><input type="text" class="form-control unit" name="p_harga[]" /></td>
<td><strong><span class="result" name="p_jumlah[]"></span></strong></td>
here my screenshoot
Screenshoot
when im run, this code success but only in row 1 and not work in row 2++
how can i fix it?
Thank you so much.
Try this
<script src="../js/plugins/jquery.js"></script>
<script>
$(function () {
$('.form-control').blur(function () {
var qty = $('.qty').val();
var total = 0;
$('.unit').each(function () {
total += parseInt(this.value);
});
// Update the total
$('.result').text(qty * total);
});
});
</script>
<input type="text" class="form-control qty" name="p_qty[]" />
<input type="text" class="form-control unit" name="p_harga[]" />
<!-- Two or more fields -->
<input type="text" class="form-control unit" name="p_harga[]" />
<input type="text" class="form-control unit" name="p_harga[]" />
<strong><span class="result" name="p_jumlah[]"></span></strong>

Categories