Home > database >  How can calculate html input values and show directly input value by jquery
How can calculate html input values and show directly input value by jquery

Time:09-06

I try to auto calculate html input values to show total values in input . here is my input form

 <div >
                       <form>
                             <div >
                                               <label for="">Price</label>
                                               <input type="text" id="price" required >
                              
                             </div>
                             <div >
                                                 <label for="">Amount</label>
                                               <input type="text" id="amount" required >
                             </div>
                             <div >
                                                <label for="">Total</label>
                                               <input type="text" id="total" required >
                             </div>
                            
                             <button type="submit" >Buy </button>
                           
                           </form>
    </div>


I want total value automatically when enter amount value and price value into input form. example

price is 3
amount is 5
total is 15

when I enter 3 and 5 total input show automatically 15

 var p1 = $('#price').val();
      var p2 = $('#amount').val();
         $('#total').val(p1*p2);
         console.log()


this code not show directly in total input but show when reload.

How can get by jquery.

CodePudding user response:

The issue is because your code is only running when the page loads. You need to hook event handlers to the input fields so that the total also gets calculated as the user enters values.

Below is a working example of how to do this. Note that the common logic which updates the total field is extracted to its own function which is called when the page loads and also when a field is updated. Also note that I added the required attribute to the total field so that the user cannot update it - it can only be set programmatically.

let $price = $('#price');
let $amount = $('#amount');
let updateTotal = () => $('#total').val($price.val() * $amount.val());

updateTotal(); // on page load
$('form input').on('input', updateTotal); // on value change
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >
  <form>
    <div >
      <label for="">Price</label>
      <input type="text" id="price" required  />
    </div>
    <div >
      <label for="">Amount</label>
      <input type="text" id="amount" required  />
    </div>
    <div >
      <label for="">Total</label>
      <input type="text" id="total" required  readonly />
    </div>
    <button type="submit" >Buy</button>
  </form>
</div>

  • Related