How can I add one to a variable at the push of a button in javascript?

410 Views Asked by At

Im trying to add one to a variable on the push of a button in javascript. Here's what I have:

<html>      
<head>      
</head>     
<body>      
<script language="javascript" type="text/javascript">           
var add = 0;            
function add1(){add++}          
document.write(add);        
</script>       
<br/>       
<input type="button" value="Add One" onclick="add1()" />    
</body>  
</html>
1

There are 1 best solutions below

0
On BEST ANSWER

Well most likely the variable add is being incremented by 1 when you push the button. However that code isn't really doing what you want.

This is probably more like what you're after:

<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var add = 0;
function add1(){
    add++;
    document.getElementById('numberField').innerHTML = add;
}
</script>
<span id="numberField"></span>
<input type="button" value="Add One" onclick="add1()" />
</body>
</html>

When you do document.write(add) it's replacing everything in the body with the value of add.

We moved the "writing the value" piece of code into the function that is called when you press the button. This is so we redraw the number after it has been incremented.

By updating the contents of an html tag instead of the entire page, we don't loose the button. The html tag has the id numberField, and can be accessed with document.getElementById('numberField');.