Search code examples
javascriptjqueryhtmlformsjquery-calculation

Need a small help in auto calculation form anyone?


anyone here good at js?

im looking for a form with following fields which would auto calculate and display the total on fly when i inpot the numbers in side the fields.

<input type="text" name="acutalprice" value="">Actual Price: 329
<input type="text" name="discount" value="">Discount: 65%
<input type="text" name="shipping" value="">Shipping: 50+

Total Amount: 165.15

on sumbit should get the total amount output

Regards


Solution

  • First things first, add jQuery library to <head></head> part of your page. You should use jQuery download page or Google's Hosted Libraries page to find jQuery library.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    

    Then, you should put <input> elements into <form></form> element and add submit button for the form.

    <form id="myForm">
        <input id="actualprice" type="number" placeholder="Actual Price">
        <input id="discount" type="number" placeholder="Discount">
        <input id="shipping" type="number" placeholder="Shipping">
        <input type="submit" value="Submit">
    </form>
    <h3 id="result"></h3>
    

    Finally, add script to the page for submitting the form.

    <script>
        $('#myForm').submit(function (event) {
    
        event.preventDefault();
    
        var actualprice = Number($("#actualprice").val().trim());
        var discount = Number($("#discount").val().trim());
        var shipping = Number($("#shipping").val().trim());
    
        var discountRate = (100 - discount) / 100;
        var result = (actualprice * discountRate) + shipping;
    
        $("#result").html("Result :" + result.toFixed(2));
    });
    </script>
    

    Good luck.