简体   繁体   中英

Get rounded values in 2 input fields that update when one of them updates

I have 3 input fields in total.

User enters a numerical value in the first. Now, when the user enters a value in the second or third one, regardless of which one it was the other updates(eg if it was the second then the third one gets updated, if it was the third one the second gets updated).

The second one is just a number, and the third one is the corresponding % of change in relation to the first input field.

You will easily see what I am talking about in the fiddle: https://jsfiddle.net/1g570e7x/

HOWEVER, I want to round the values of the second and third input field as soon as the input has happened and then update the corresponding field like before of course.

For instance: The user has entered 50 into the first input, then enters 40 into the second that gets changed to 40.00 and the third field gets changed to 20.00

Here is the HTML:

<input id="input1" type="number"/>Stock<br><br>
<label for="input2">Remainder</label>
<input id="input2" type="number"/><br>
<label for="input3">Percentage of loss</label>
<input id="input3" type="number"/>%<br>

And the jQuery:

$(document).ready(function(){

    $('#input2').on('input',function(){
    var stock=$('#input1').val();
    var value=$('#input2').val();
    $('#input3').val((stock-value)/stock*100);
  });

    $('#input3').on('input',function(){
    var percnt=$('#input3').val();
    var stock=$('#input1').val();
    $('#input2').val(stock-(stock*percnt/100));
  });

  $('#input1').on('input',function(){
    if($('#input2').val()!=''){
      $('#input2').trigger('input');
    }

    if($('#input2').val()!=''){
     $('#input3').trigger('input');
    }

  });

});

You can use parseFloat to convert a string into a float, and then use the float's toFixed function to set it to the correct number of decimal places:

 var value = '33.234234234'; var float = parseFloat(value); alert(float.toFixed(2)); 

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