简体   繁体   中英

Populating a text box with the results of a calculation

I have this form where a user enters price and quantity, soon after the mouse leaves the 'Quantity' text box, I want the TotalPrice text box to be populated with result of Price * Quantity. The following is my jQuery code, however the TotalPrice text box does not get populated with the result. Hope someone can advise me on how to go about getting it right.

$("#quantity").mouseleave (function () {
    var i = $("#price").val();
    var k = $("#quantity").val();
    var total = i*k;
    $("#totalprice").val(total);
});

The problem with your code is that it is getting executed ONLY ONCE as soon as the ready function is called. You need to attach a listner to the action element

$(document).ready(function() {
    $("#quantity").mouseleave(function(){
        var i = $("#price").val();
        var k = $("#quantity").val();
        var total = i*k;    
        $("#totalprice").val(total);  
    });         
});

You can use various event listners such as onchange, onfocusout, blur, onkeyup depending on how and when you want the changes to happen. For more info on types of events and all for jquery only - https://api.jquery.com/category/events/

You need to use blur event handler of those two textboxes. Try this:

$(document).ready(function() {
  $("#price").on("blur", calculate);
  $("#quantity").on("blur", calculate);
  //If you want to do the calculation when the page renders:
  calculate();
});

function calculate(){
  var i = $("#price").val();
  var k = $("#quantity").val();
  var total = i*k;    
  $("#totalprice").val(total);                
}

As trincot mentioned in the comment below, you can merge the two events in one line since they call the same function:

$("#price, #quantity").on("blur", calculate);

I think you want this

jQuery(document).ready(function($) {
    var price = $("#price");
    var qty = $("#quantity");
    var total = $("#totalprice");
    /* CREATE VARIABLES ON DOCUMENT READY, 
       BECAUSE YOU WANT TO CACHE THE DOM SELECTION */
    qty.on("blur", function(){
         var i = price.val();
         var k = qty.val();
         total.val(i * k);
    });
});

working fiddle ==> https://jsfiddle.net/tonysamperi/xqxm3900/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM