![](/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.