tyrlaka
tyrlaka

Reputation: 154

Auto calculate input field

I have 2 input fields, one input and the other is disabled. I need when input numbers in the input fiend, the disabled field to show this number/100. I try to use <span> with this javascript:

$(document).ready(function(){
    $('#sum').keyup(function(){
        $('#result').text($('#sum').val() / 100);
    });   
});

But it didn't work. This is my input fields:

<input type="text" name="sum" id="sum" value="php" size="15" />
<input type="text" name="result" id="result" size="15" value="HERE THE RESULT" disabled />

Upvotes: 1

Views: 2665

Answers (2)

Bhavesh G
Bhavesh G

Reputation: 3028

You use val() instead of text().

Another point is to check for division by zero error just to be safe. Here is what your code should be.

$('#sum').keyup(function(){
    var res = $('#sum').val() / 100;
    if (res == Number.POSITIVE_INFINITY || res == Number.NEGATIVE_INFINITY || isNaN(res))
        res = "N/A"; // OR 0
    $('#result').val(res);
});

Upvotes: 1

jrath
jrath

Reputation: 990

Use val() not text() for input field.

$(document).ready(function(){
        $('#sum').keyup(function(){
            $('#result').val($('#sum').val() / 100));
        });   
    });

Upvotes: 0

Related Questions