skip to Main Content

I can’t get this to work and I can’t think of any way to make this work,
I’m trying to have a button value change to a var every time you press it.

code-

<input onclick="change(this)" type="button" value="0" id="myButton1" />

<script>
  value="1"
 function change(this)
{
target.value = parseInt(target.value) + 1;
}
</script>

2

Answers


  1. You need to declare the variable outside of the function. Here is the code with the fix.

    var click = 0;
    function change() {
      click = click + 1; // up the var
      document.getElementById("myButton1").value = click;
    }
    <input onclick="change()" type="button" value="click" id="myButton1" />
    Login or Signup to reply.
  2. You need to declare the variable outside the function and then increment it inside, otherwise you just reset it every time the function runs. I would also pass the event into the function so you can change the value of the clicked button rather than getting the element by id each time

    <input onclick="change(event)" type="button" value="0" id="myButton1" />
    
    <script>
      // declare variable outside function and set to current value
      var click = parseInt(document.getElementById("myButton1").value, 10);  
                   
      function change(e) {
        e.preventDefault();              // if this is in a form, you may want to add this so the form doesn't submit
        click += 1;                      // increment with +=
        e.currentTarget.value = click;   // change value of clicked button
      }
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search