Search code examples
javascriptinput-field

How can i perform a specific math calculation inside an input field and populate the result to another?


My question is pretty much simple. What i want is exactly as i described on title. I have 2 input fields (field1 and field2). When i add a number in the field1 i need to divide it with a specific number (eg 1.38) and populate the result in the field2 automatically.

Right now i am using this code to populate the data form field1 to field2 but i dont know how can i perform the division math calculation

<input type='text' id='field_1'>
<input type='text' id='field_2'>

$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});

Here is the JSFiddle


Solution

  • That is a pretty basic programming operation, however, code below as follows:

    $(document).ready(function () {
      $('#field_1').on('change', function (e) {
        var result = parseFloat($(this).val()) / 1.38; // Change 1.38 value with the desired number
        $('#field_2').val(result);
      });
    });