简体   繁体   中英

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

<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) .

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. You need to move the code to a change event:

$("#height").change(function(){
   var weight = $("#weight").val();
   var height = $("#height").val();
   var bmi = weight/height;
   $("#bmi").val(bmi);
});

use parseInt like this:

$("#bmi").click(function (){
    var weight = parseInt($("#weight").val());
    var height = parseInt($("#height").val());
    var bmi = weight/height;
    $("#bmi").val(bmi);
}

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