faq
faq

Reputation: 3076

Why cant i enter decimal values in input in the following case

Before anything you need to see the effect:

jsFiddle

As you can see it is a calculator where you can put a value anywhere and covert it to other values, but the problem is that i cant enter decimal int values like 0.3 or 0.999. What is the cause of this?

var id = {
    mm: 1,
    cm: 10,
    m: 1000,
    km: 1000000
};

$('input.bx').on('keyup', function() {

    var t = $(this).val();
    var i = id[$(this).attr("id")];
    var v = parseInt(t, 10);

    for (pp in id) {

        if (t !== '') {
            $("#" + pp).val(v / id[pp] * i);
        } else {
            $(".bx").val('');
        }

    }

});

<input type='text' class='bx' id='mm'> Milimeter<br>
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br> 

Upvotes: 0

Views: 307

Answers (5)

Anil Kumar
Anil Kumar

Reputation: 165

a working fiddle here

you have to use parseFloat and dont try to set the current focused element value cause you are over riding it while typing.

Upvotes: 1

Mohamed Abo Elenen
Mohamed Abo Elenen

Reputation: 54

this example is working fine

http://jsfiddle.net/Mohamed_aboelenen/D6T7j/1/

$('input.bx').on('keyup', function() {

var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseFloat(t, 10);
var a = $(this).attr("id"); // the textbox you write in
for (pp in id) {
    if (t !== '' ) {
        if(a != pp){  // make changes to any textbox except the one you write in
        $("#" + pp).val(v / id[pp] * i);
        }
    } else {
        $(".bx").val('');
    }

}


});

Upvotes: 1

Anton
Anton

Reputation: 32581

1.First you need to use parseFloat because int cant have decimals. 2.Second i would use onChange. http://jsfiddle.net/Kfkjy/10/

Upvotes: 2

Man Programmer
Man Programmer

Reputation: 5356

$('input.bx').on('blur', function() {

    var t = $(this).val();
    var i = id[$(this).attr("id")];
    var v = Number(t, 10);

    for (pp in id) {

        if (t !== '') {
            $("#" + pp).val(parseFloat(v / id[pp] * i));
        } else {
            $(".bx").val('');
        }

    }

});

Upvotes: 0

Miha Rekar
Miha Rekar

Reputation: 1546

parseInt is the "problem" since it returns integer - decimal values are not integer but floats. If you want that you must replace it with parseFloat.

Upvotes: 3

Related Questions