Search code examples
jqueryjquery-calculation

show total in jquery ajax without click on text field


I am using this to calculate total. Here is the total script

<!DOCTYPE HTML>
<html lang="en-IN">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="js/jquery1.7.2.js"></script>
</head>
<body>
  <script type="text/javascript">
    jQuery(document).ready(function(){
      jQuery("#quantity, #unit_price, #tax").on('change',function(event){
        var subtotal = jQuery("#quantity").val() * jQuery("#unit_price").val();
        var total = subtotal + (subtotal  * jQuery("#tax").val() / 100);
        jQuery("#total").val(total);
      });
    });
  </script>
  <table>
    <tr>
      <td>
        <label for="unitcost">Unitcost</label>
        <input type="text" id="unit_price" />
      </td>
     </tr>
     <tr>
      <td>
        <label for="quantity">Quantity</label>
        <input type="text" id="quantity" />
      </td>
    </tr>
    <tr>
      <td>
        <label for="tax">Tax</label>
        <input type="text" id="tax" />
      </td>
    </tr>
    <tr>
      <td>
        <label for="total">Total</label>
        <input type="text" id="total" />
      </td>
    </tr>
  </table>
</body>
</html>

But there is one problem. Every time I have to click the text field to get the result. I want that when user will enter the values in their fields it should show the total without click on input fields. I think jquery ajax will work here but don't know how to implement that in this. Any help and suggestions will be appreciable.


Solution

  • use the .keyup() it will show the total without click on input fields

    jQuery("#quantity, #unit_price, #tax").keyup(function(event){
    

    or

    jQuery("#quantity, #unit_price, #tax").on('keyup',function(event){