+ 1
[SOLVED] How do I add a value if I press a button?
I mean, if the value is 0 and then we pressed the button and it will change in to 1, then if we pressed the button again, I want it change into 2 ? [Problem solved, thanks for all ☺]
5 Antworten
+ 3
Html:
If you won't reuse the function it is not necessary to set one.
You can create button anywhere in your document.
<body>
<div>X value: <span id="Xval">0</span>
</div>
<br>
<input type="button" value="X + 1" onclick="document.getElementById('Xval').innerHTML=++x">
<script>
var x = 0;
</script>
</body>
+ 1
You need to use inputs and forms.
<form>
<input type="button" class="button" onclick="addone()">
</form>
If you want the button to show the current value you have to do something much more advanced. I'm not sure how to add JavaScript in a value="".
And the JS:
var x = 0;
function addone()
{
x++;
}
+ 1
@Zmn
1. You have create 2 functions to add 1.
Why not only one.
function count() {
document.getElementById("view").innerHTML = counter++;
}
This function will show counter then will increment it. When value in document is 2, counter = 3.
2. You have missed a quote in your html code
- 1
//Javascript
var counter = 1;
var add = (function() {
return function() {
return counter++;
}
})();
function count() {
document.getElementById("view").innerHTML = add();
}
//HTML
<button onclick="count()>Add</button>
<p id="view">0</p>