+ 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 ☺]

4th Sep 2016, 11:56 AM
Faisal Hanif
Faisal Hanif - avatar
5 Respostas
+ 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>
6th Sep 2016, 5:22 AM
Tama Lebarbu
Tama Lebarbu - avatar
+ 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++; }
4th Sep 2016, 10:14 PM
Oscar
Oscar - avatar
+ 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
7th Sep 2016, 8:10 AM
Tama Lebarbu
Tama Lebarbu - avatar
- 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>
7th Sep 2016, 7:29 AM
zmn