PHP Ferrari
PHP Ferrari

Reputation: 15616

How to use onchange in HTML

I have two text box in html ie:

<input type="text" value="" id="a" name="a" />
<input type="text" value="" readonly="true" id="b" name="b" />

Now if i enter only a number in element id "a" then the product of inserted number by 2 will be appear in element id "b".

Like: While i m typing a number let say 11 in element "a" then on the same time 11*2 ie: 22 will appear in element "b" and if enter backspace or delete any number on the same time change will appear in element "b".

To get my required result i create a function like

onchange = function totalAmount()  
{
    var value = $("#a").val();

    if ( (value > 0) && (value != "") )
    {
        $("input:text[name=b]").val(2 * value);
    }
    else
    {
        $("input:text[name=getCredit]").val("");
    }
};

It fulfill 80% of my requirement as it will make change in element "b" if i click on any were after insert a number.

Upvotes: 0

Views: 599

Answers (3)

Viktor
Viktor

Reputation: 7167

i think using the onkeyup event might help

<input type="text" value="" id="a" name="a" onkeyup="calcTotalAmount()" />
<input type="text" value="" readonly="true" id="b" name="b" />

<script>

    function calcTotalAmount() {

        var a = document.getElementById("a");
        var b = document.getElementById("b");

        if (!isNaN(a.value)) {
            b.value = a.value * 2;
        }
    }

</script>

Why onkeyup?

Onkeydown event fires when key is pressed, onkeyup event fires when key is released and the event onkeypress fires if the onkeydown is followed by onkeyup,

and in the time of onkeydown the input field does not containt the value yet.

Upvotes: 1

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10762

If you want a call back on every key press you can use the onKeyPress attribute.

(If you are using a library like JQuery/prototype/etc there is probably a nice way of observing a field using the library)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I see that you are using jQuery. You could bind to the change event of the textbox:

$('input:text[name=a]').change(function() {
    // invoked when the value of input name="a" changes
    // get the new value
    var value = $(this).val();
    // update the value of input name="b"
    $('input:text[name=b]').val(2 * value);
});

This event will be raised when the input loses focus. You could also take a look at keypress and keyup events.

Upvotes: 1

Related Questions