简体   繁体   中英

How can I get the value of 2 inputs, calculate them and put the result in another

I need to refactor this code to improve performance, I take the value of two inputs and I need to calculate them and display it in another

            var price;
            var percentage;
            var value;

            function total() {
                value = ((price* (percentage/ 100)) + parseFloat(price));

                $("#Total").val(value.toFixed(2));
            }

            $("#price").keyup(function () {
                price= $(this).val();
                total()
            });
            $("#percentage").keyup(function () {
                percentage= $(this).val();
                total()
             
            });
         

You shouldn't use global variables like this, they could cause race conditions.

// this self executing function will prevent the *Field variables to be bound to your browsers' window variable. 
(function() {   

  let priceField = $("#price");
  let percentageField = $("#percentage");
  let totalField = $("#Total");

  function total() {
    let price = priceField.val();
    let percentage = percentageField.val();
    
    let value = (price * (percentage/ 100)) + parseFloat(price);

    totalField.val(value.toFixed(2));
  }

  priceField.keyup(function () {
    total()
  });
  percentageField.keyup(function () {
    total()
  });

})()

I have to say, this is a solution for your question, but it's not the nicest one out there. But based on my guess, this solution needs to be simple.

A few extra tips would be to selectively search for input fields like $("input#price") to prevent any other potential collisions, although an id should be unique.

I also would suggest to add some protection in the code. If anybody entered some non numeric values, what should happen. Should they be stripped from the input before the calculations are made, or should they trigger an error to the user stating that the user's input is not valid.

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