Shubharaj Buwa
Shubharaj Buwa

Reputation: 9

How to change values as a user enters in javascript

<div class="box2">Enter taxable income :-
    <br>
    <input type="text" id="entry" onchange="calc()" required></input>
    <input type="submit" name="submit" value="Submit" onclick="calc()"></input>
    <p>Income :-
        <br>
        <input type="text" id="res"></input>
    </p>
    <p>Your tax bracket :-
        <br>
        <input type="text" id="tbra"></input>
    </p>
    <p>Tax :-
        <br>
        <input type="text" id="tax"></input>
    </p>
    <p>Education Cess :-
        <br>
        <input type="text" id="ec"></input>
    </p>
    <p>Higher Education Cess :-
        <br>
        <input type="text" id="hec"></input>
    </p>
    <p>Total Tax :-
        <br>
        <input type="text" id="ttax"></input>
    </p>
</div>

In the above form how can I change values in the text boxes as I enter new values. Currently either I have to press the enter key (onchange) or press the submit button. I am using JavaScript functions.

Upvotes: 0

Views: 56

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

jsBin demo

Have you thought about "What if a user pastes a value"?

Also <input /> is invalid HTML markup,
inputs are void elements therefore should not have a closing tag.

HTML:

    <div class="box2">
        Enter taxable income:<br>
        <input type="text" id="entry" required>
        <p>
            Income:<br>
            <input type="text" id="res">
        </p>
        <p>Your tax bracket:<br>
            <input type="text" id="tbra">
        </p>
        <p>
            Tax:<br>
            <input type="text" id="tax">
        </p>
        <p>
            Education Cess:<br>
            <input type="text" id="ec">
        </p>
        <p>
            Higher Education Cess:<br>
            <input type="text" id="hec">
        </p>
        <p>
            Total Tax:<br>
            <input type="text" id="ttax">
        </p>
    </div>

As you can see I've removed the inline JS which is considered bad practice.
Move all your logic into JS:

function id(v){return document.getElementById(v);}

var entry = id("entry");
var res   = id("res");

function calc() {
    res.value = parseInt(entry.value, 10) + 100;
}

entry.addEventListener("input", calc, false);

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

You could use the onkeypress event instead, which activates whenever the user types, instead of when the form actually changes (loses focus):

<input type="text" id="entry" onkeypress="calc()" />

Upvotes: 1

Related Questions