DragonSlayr15001
DragonSlayr15001

Reputation: 47

HTML/Javascript keypad function isn't working

I am making a page for a school project, and I am trying to make a keypad for a passcode system. However, I don't know how to get the keys to work. Looking it up, I have found multiple working keypads, however, I don't know what parts of their code I would have to add to my page to make it work.

The code that follows is currently what I have attached to the onclick part of each of the buttons:

    <script>
      function kpclick(){
        var current = document.getElementById("tbInput").value;
        var append = this.innerHTML;
        if (current.length < 4) {
          if (current=="0") {
            document.getElementById("tbInput").value = append;
          } else {
            document.getElementById("tbInput").value += append;
          }
        }
      }
    </script>

The "tbInput" mentioned is a textbox underneath the keypad in the same div that later will be hidden and (hopefully) disabled. If there is no solution that allows the keypad to be used while the textbox is disabled, I will likely move it outside of the div the keypad is in.

When I press any of the buttons currently, nothing happens. What's happening here?

Upvotes: 0

Views: 80

Answers (1)

Daniel
Daniel

Reputation: 35684

I'm assuming this is meant to be the button context. You can pass it with onclick="kpclick(this)".

function kpclick(target) {
  var current = document.getElementById("tbInput").value;
  var append = target.innerHTML;
  if (current.length < 4) {
    if (current == "0") {
      document.getElementById("tbInput").value = append;
    } else {
      document.getElementById("tbInput").value += append;
    }
  }
}
<button onclick="kpclick(this)">0</button>
<button onclick="kpclick(this)">1</button>
<input id="tbInput">

Upvotes: 1

Related Questions