Reputation: 185
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
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
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