[英]Get rounded values in 2 input fields that update when one of them updates
I have 3 input fields in total. 我总共有3个输入字段。
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/ 您将很容易在小提琴中看到我在说什么: 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 例如:用户在第一个输入中输入了50,然后在第二个输入中输入了40,将其更改为40.00,将第三个字段更改为20.00。
Here is the HTML: 这是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: 和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: 您可以使用parseFloat
将字符串转换为浮点数,然后使用浮点数的toFixed
函数将其设置为正确的小数位数:
var value = '33.234234234'; var float = parseFloat(value); alert(float.toFixed(2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.