[英]How do i take values of 2 input fields which are numbers, then divide using Jquery and display the result to another input?
I have two input fields 我有两个输入字段
<label>WEIGHT</label>
<input type="number" name="weight" id="weight" class="form-control" placeholder="weight in KG">
<label>HEIGHT</label>
<input type="number" name="height" id="height" class="form-control" placeholder="Height in Meters">
I want to take the value of weight and divide it by the height then assign the result to this input field in realtime using JQuery 我想将权重值除以高度,然后使用JQuery将结果实时分配给此输入字段
<label>BMI</label>
<input type="text" name="bmi" id="bmi" class="form-control" placeholder="weight/height">
I have tried this but its not working 我已经尝试过了,但是没有用
$(document).ready(function(){
var weight = $("#weight").val();
var height = $("#height").val();
var bmi = weight/height;
$("#bmi").val() = bmi;
});
When you use jQuery's .val
to set a value, you need to pass the new value inside the parantheses, ie: .val(newValue)
. 当您使用jQuery的
.val
设置值时,您需要在括号内传递新值,即: .val(newValue)
。
So you code should be like this: 因此,您的代码应如下所示:
$("#bmi").val(bmi);
Also, there's no sense in doing these calculations on document.ready
, since the inputs will have no value. 另外,对
document.ready
进行这些计算也没有意义,因为输入将没有任何价值。 You need to move the code to a change
event: 您需要将代码移至
change
事件:
$("#height").change(function(){
var weight = $("#weight").val();
var height = $("#height").val();
var bmi = weight/height;
$("#bmi").val(bmi);
});
use parseInt
like this: 像这样使用
parseInt
:
$("#bmi").click(function (){
var weight = parseInt($("#weight").val());
var height = parseInt($("#height").val());
var bmi = weight/height;
$("#bmi").val(bmi);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.