Skip to content Skip to sidebar Skip to footer

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

<table align="center">
    <tr>
        <td align="center">Quantity:</td>
        <td colspan="2"></td>
    </tr>
    <tr>
        <td><input type="number" min="64" max="9999" name="quantity" /></td>
        <td>&nbsp;&nbsp;@&nbsp;&nbsp;$345.50/per item&nbsp;&nbsp;=&nbsp;&nbsp;</td>
        <td data-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: <input type="text" id="quantityField">
  <div>Total: <span id="totalField">0</span> $ (5$/item)</div>
</form>


<script src="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 program
  var pricePerItem = 5;
  
  // This code executes when the quantityField elements value changes
  $('#quantityField').on('input',function(event){

    // 1. Read quantity
    var quantity = $(this).val();
    
    // 2. Calculate total
    var 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:

https://jsfiddle.net/LzLep9ez/


Post a Comment for "Trying To Get Total Amount Based On User Input"