Search code examples
javascriptintegerdecimalauto-update

Auto Update form field from integer to decimal


I have two form fields for users to enter weight in kg and length in meters, most users consider the length in centimeters which gives wrong calculations. can I have a way to auto update form in the case of entering integer ? ( e.g. 170 to be automatically converted to 1.7 ) ?


Solution

  • You may check if the value is an integer like that:

    var isInt = function(n) {
       return n % 1 === 0;
    }
    

    Here is a js fiddle showing this in action http://jsfiddle.net/krasimir/6e72q/

    HTML

    <input type="text" id="field"/>
    

    JS

    var field = document.getElementById("field");
    field.addEventListener("change", function() {
        var value = field.value;
        if(isInt(value)) {
            field.value = value = value / 100;
        }
    });
    var isInt = function(n) {
       return n % 1 === 0;
    }