Trying To Get Total Amount Based On User Input
I have a page where a user can submit a form, that works fine, but I want to have a quantity field where the user can input a number and in the totals box it will show the total as
Solution 1:
See this JSFiddle (notice the added data-product-price
attribute)
HTML
<tablealign="center"><tr><tdalign="center">Quantity:</td><tdcolspan="2"></td></tr><tr><td><inputtype="number"min="64"max="9999"name="quantity" /></td><td> @ $345.50/per item = </td><tddata-product-price="345.50"></td></tr></table>
JavaScript
$(function(){
$("input[name='quantity']").on("input", function(){
var $outputCell = $(this).parent().siblings("[data-product-price]").eq(0);
$outputCell.html((+$outputCell.data("product-price") * +$(this).val()).toFixed(2));
});
});
Solution 2:
A minimal example where jQuery and Javascript is used could be:
<form>
Quantity: <inputtype="text"id="quantityField"><div>Total: <spanid="totalField">0</span> $ (5$/item)</div></form><scriptsrc="https://code.jquery.com/jquery-2.1.4.min.js"></script><script>// The line above loads jQuery// Javascript code goes here. You would normally have this in a separate file.// Somehow fetch the desired price from your programvar pricePerItem = 5;
// This code executes when the quantityField elements value changes
$('#quantityField').on('input',function(event){
// 1. Read quantityvar quantity = $(this).val();
// 2. Calculate totalvar total = pricePerItem * quantity;
// 3. Update total field
$('#totalField').text(total);
});
</script>
Note that this is a minimal example that does not follow best practises in programming javascript with regards to safety, code placement etc., but it might just help you on your way.
Solution 3:
You could try by echo the price/per product inside a disabled input, or by adding an hidden input which value is the price/per product.
Then you can try this JS:
$('your_quantity_input').on('change', function() {
var quantity = $(this).val();
var price = $('your_hidden_input').val();
var total = quantity * price;
$('your_td_total').html(total);
});
This is by using jQuery.
Here is the working example:
Post a Comment for "Trying To Get Total Amount Based On User Input"