How to update price dynamically based on quantity using jQuery? - javascript

I have build a shopping cart where I want to update the price based on Quantity..But the problem I'm facing is using following javascript code that for the first item i could update the price based on Quantity but for the second item or next item i couldn't ..Can anyone help me out to find the Error please.
Here's my html :
<td class="total_price table-default total" >${{$row->price}}
<span></span></td>
<td class="qty table-default">
<input type="number" class="quantity" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> ×${{$row->p_price}}
Here's the jQueryPart:
$(".quantity").change(update);
function update()
{
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('.total').html("$"+total);
}

Remove the following block:
$("#quantity").each(function(i){
so the function is:
function update(){
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('#total').html("$"+total);
}

Related

How do I multiply values from different inputs to get a total using Javascript?

I am trying to do a shopping cart where I want the total to automatically change after the quantity is inputted (the total is the price times the quantity). I'm trying to use Javascript for this and I just can't seem to get it as it is coming up with null and before it said NaN.
PS: It is a console log at the moment just to see if it works, but I will need it to go into the total input tag.
HTML:
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="$18.95">
JavaScript:
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total = price * quantity;
console.log(total);
}
Try this:
function calcTotal() {
// remove $ sign and parse Float price
var price = parseFloat(document.getElementById("price").value.substr(1));
// parse float quantity
var quantity = parseFloat(document.getElementById("quantity").value);
var total = price * quantity;
//pass calculated value to input with id total
document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">
Any operation that involves a string returns NaN, however you should
coerce your input values as Number
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total =Number(price) * Number(quantity);
console.log(total);
}
Using Number vs parseFloat
So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):
parseFloat('1x'); // => 1
Number('1x'); // => NaN

Dynamic Table Quantity update Javascript

I was trying to update my quantity inside a table where list of rows are there. But i want to get the specific row with the quantity.
<td class="qty">
<div class="quantity-spinner">
<input type="number" name="product" class="prod_qty" value="{{$food->quantity}}" data-id="{{$food->id}}" />
</div>
</td>
// This is inside a loop so multiple row can be created.
javascript i have used :
$(":input").bind('keyup mouseup', function () {
var qty = $('.prod_qty').val()
var food_id = $('.prod_qty').attr("data-id")
});
But the problem is I got always first row food_id & qty not the specific one i wanted to update. How can i that specific row value?
Well take the value of the current element:
$(":input").bind('keyup mouseup', function () {
var qty = $(this).val()
var food_id = $(this).attr("data-id")
});

Jquery loop 2D form inputs and calculate values per array key

I am trying to calculate a ticket total based on user input on a form using 2 dimensional names. I have been searching for 2 days on how to pull all the values at once from each key in the input field names.
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
When the user enters the price in the corresponding area, the total for the whole order needs to be calculated and displayed at the bottom of the screen using javascript / jQuery.
Here is the function :
function calculate_ticket(){
var total = 0;
var data = $("input[name^='service[]']").serializeArray();
$.each(data, function(i, field){
$("#ticket_total").append(field.name + ":" + field.value + "<br />"); // for debugging.
});
console.debug(data);
$('#ticket_price').html("$" + total.toFixed(2));
}
What I am hoping to do is pull all the data from each key at once and simply multiply the 'price' by the 'qty' then add that to the 'ticket_price'. The form 'service' input area can have and unlimited number of entries.
I figured a way to do this finally :)
I switched around the name dimension from service[]['qty'] to service['qty'][] and used .serializeArray() on both qty and price. Here is the function :
function calculate_ticket(){
var total = 0;
var price = $("input[name^='service[\\'price\\']']").serializeArray();
var qty = $("input[name^='service[\\'qty\\']']").serializeArray();
$.each(price, function(i, field){
total += qty[i].value * field.value;
});
$('#ticket_price').html("$" + total.toFixed(2));
}

I cannot find why this simple JS isn't working. (Sales Tax Calculator)

My HTML is a simple entry form like this:
<div id="taxCalc">
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" >
<span id="subtotal_message">Enter order subtotal</span><br />
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" >
<span id="tax_rate_message">Enter sales tax rate (99.9)</span><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br />
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" onclick="calculate_click()">
<input type="button" id="clear" value="Clear" onclick="clear_click()">
And my JS is 2 simple functions...
var subtotal, taxRate, salesTax, total;
function setValues() {
subtotal = document.getElementById("subtotal").value;
taxRate = document.getElementById("tax_rate").value;
salesTax = document.getElementById("sales_tax").value;
total = document.getElementById("total").value;
}
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
I have included a JS Fiddle link for more information as well: http://jsfiddle.net/tjhillard/nkHxe/1/
I want the sales tax and the total to display inside the appropriate fields when the "Calculate" button is clicked.
Thank you in advance for your help!
you just need to update the values back:
change this:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
into:
function calculate_click() {
setValues();
salesTax = (subtotal * taxRate) / 100;
total = subtotal + salesTax;
// place the value in the form
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
updated version of your code: http://jsfiddle.net/nkHxe/4/
It should be in the following way:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
http://jsfiddle.net/nkHxe/5/
P.S
Keep in mind that your code is bad-organized ))
1) You don't write back the values. Maxim and Balexandre already showed how.
2) total is a concatenation of a string with a number which leads to a string again. This has not been solved by Maxim and Balexandre.
By directly reading from the input field, you get strings back. So, parse them first into numbers. Example:
parseInt(document.getElementById("subtotal").value)
In your code, you have the issue when calculating total as explained above. The issue does not occur for salesTax because the strings are automatically converted thanks to the math operations you apply.
Hope this helps.
Updated, Fully Working, total code Fixed where Integers were Passed (Concatenated) as Strings.
Code added,
subtotal = parseInt(document.getElementById("subtotal").value)
total = parseInt(document.getElementById("total").value)
Link,
http://jsfiddle.net/nkHxe/150/
Thanks to TJH, Balexandre, Maxim and Patrick :)

How to add value to a number using range inputs for a cost calculator?

I'm trying to create a cost calculator. Basically I have values within checkbox inputs and as they are checked, they are added together using jQuery.
$('.option').click(function() {
var total = 0;
$('.option:checked').each(function(){
total += parseInt($(this).val());
});
$('.estimate').html('$' + total);
});
<input class="option" type="checkbox" value="1000" />
<input class="option" type="checkbox" value="200" />
<input class="option" type="checkbox" value="750" />
So in the above example, the total would be 1950. That part of the function works fine, but I want to add two range sliders in to the equation.
<input class="range" type="range" min="0" max="3">
<input class="range" type="range" min="0" max="3">
Each of the 4 positions of the slider would increase the value added to the overall total. How could I add the range slider positions in to the above function?
Here is the jsFiddle: http://jsfiddle.net/2MLKc/
Just use the input's change event:
http://jsfiddle.net/EfrainReyes/2MLKc/4/
$(document).ready(function() {
var total;
var addToTotal = function(){
total += parseInt(this.value, 10);
};
var compute = function() {
total = 0;
$('.option:checked,.range').each(addToTotal);
$('.estimate').text('$' + total);
};
$('.option, .range').change(compute);
});
Here is simple change to what you have to make it work.
$('input').change(function() {
var total = 0;
$('.option:checked').each(function(){
total += parseInt($(this).val());
});
$('.range').each(function(){
total += parseInt($(this).val());
});
$('.estimate').html('$' + total);
});
http://jsfiddle.net/6DbFH/
Well, you could do something quite similar like with the checkbox. With jQuery you can get the value of a slider input with $(selector).val().
But I recommend to abstract the calculation on another function and call it from the $('.option').click(function()... and the $('.range').change(function()...

Categories