zZShort_CircuitZz
zZShort_CircuitZz

Reputation: 185

Buttons to increment/decrement a value on screen

I have something like this in an HTML file:

<html>

    <body>

    <script type = text/javascript">
        var value = 0;

        add(x){
            x++;
            document.write(x);
        }
    </script>

    <form>
        <input type = "button" value = "Add one" onClick = "add(value)" >
    </form>

    <body> 

</html>    

When I run this and click the button, the page will just update and display only the new value. How can I change this so that it's just a real time update, and the "Add one" button remains on the screen?

I think I need to have something like a "field" to display the value, and just get that field id, but I'm not sure if that's the right way of thinking.

Upvotes: 1

Views: 7455

Answers (2)

AstroCB
AstroCB

Reputation: 12367

Just use a span:

<form>
    <input type="button" value="Add one" onclick="add();"/>
</form>
<span id="field">0</span>

Then, use document.getElementById() and innerHTML to update it:

var value = 0;

function add() {
    value++;
    document.getElementById("field").innerHTML = value;
}

var value = 0;

function add() {
    value++;
    document.getElementById("field").innerHTML = value;
}
<form>
    <input type="button" value="Add one" onclick="add();"/>
</form>
<span id="field">0</span>

Upvotes: 2

adam
adam

Reputation: 555

In your html add an id in a div for example addOne

<html>

    <body>

    <script type = text/javascript">
        var x = 0;

function increment(value){
    document.getElementById('addOne').innerHTML = ++x;
}
    </script>

    <form>
        <input type = "button" onClick = "increment(value)" >
    </form>
<div id ="addOne"></div>

    <body> 

</html>    

Upvotes: 1

Related Questions