![](/img/trans.png)
[英]How do you add the values from input fields and update another field with the result in jQuery?
[英]How do i take values of 2 input fields which are numbers, then divide using Jquery and display the result to another input?
我有两个输入字段
<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">
我想将权重值除以高度,然后使用JQuery将结果实时分配给此输入字段
<label>BMI</label>
<input type="text" name="bmi" id="bmi" class="form-control" placeholder="weight/height">
我已经尝试过了,但是没有用
$(document).ready(function(){
var weight = $("#weight").val();
var height = $("#height").val();
var bmi = weight/height;
$("#bmi").val() = bmi;
});
当您使用jQuery的.val
设置值时,您需要在括号内传递新值,即: .val(newValue)
。
因此,您的代码应如下所示:
$("#bmi").val(bmi);
另外,对document.ready
进行这些计算也没有意义,因为输入将没有任何价值。 您需要将代码移至change
事件:
$("#height").change(function(){
var weight = $("#weight").val();
var height = $("#height").val();
var bmi = weight/height;
$("#bmi").val(bmi);
});
像这样使用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.