Reputation: 25
How do I change the HTML itself when I press a button? When I press a button in this case, the value is stored as "displayCount". Is there a way in which I can directly see the count on the HTML code? If it was press one time, I could see the number 1 on the HTML itself, not as a variable?
Thank you!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> </title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function() {
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
For example, if button was pressed once, one of the line would change from
<p>The button was pressed <span id="displayCount">1</span> times.</p>
Upvotes: 1
Views: 642
Reputation: 11
<script>
var count = 0;
function counts()
{
var result = document.getElementById('txtbxid');
count ++ ;
result.value = count;
}
</script>
<input type="text" id="txtbxid" name="txtbxid">
<input type="button" id="add" name="add" value="add" onClick="counts()">
Upvotes: 0
Reputation: 4718
I guess you might want to use parseInt()
explicitly increment the count
as an integer like this:
var count = parseInt(display.textContent,10);
Your code could go like this:
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var count = parseInt(display.textContent,10);
button.onclick = function(){
count++;
display.innerHTML = count;
}
DEMO : http://jsfiddle.net/naokiota/9dQjv/2/
The document of the parseInt()
is here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Hope this helps.
Upvotes: 0
Reputation: 308
Here is my jsfiddle to your problem.
I delete the varible count
you used, and just use the number on your HTML, it works well.
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
display.innerHTML = ++display.innerHTML;
}
Thanks,
Edison
Upvotes: 0
Reputation: 2831
This Fiddle works as you want..
i changed your script into :
var count = 0;
function countIt(){
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
count++;
display.innerHTML = count;
}
and your HTML to :
<input type="button" onclick="countIt()" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
Upvotes: 2
Reputation: 1006
hope this will help you
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Count</button>
<p>The button was pressed : <a id="clicks">0</a></p>
Upvotes: 0