Search code examples
javascriptdom-events

Pure JavaScript on screen keyboard issue


I have an on-screen keyboard and 5 input boxes. My problem is when I focus on an input box and input something, nothing will happen. I want to add input every time I focus on an input box.

Here's my simple code. This code only works for 1 input field. I want to make this work for 5 or 4 input fields.

function writeKey(key){
  if(key){
    if(key == "Enter"){
      key = "10";
     } else if(key == "tab"){
      document.getElementById("feld1").value += "\t ";
    } else if(key=="backspace"){
      document.getElementById("feld1").value=document.getElementById("feld1").value.slice(0,-1);
    } else if(key==" "){
      document.getElementById("feld1").value += " ";
    } else {
      document.getElementById("feld1").value += String.fromCharCode(key);
    }
  }
}

Solution

  • Take a look at document.activeElement which points to currently focused element.

    You can rewrite your code like this using it:

    function writeKey(key){
      var el = document.activeElement;
      if(key){
        if(key == "Enter"){
          key = "10";
         } else if(key == "tab"){
          el.value += "\t ";
        } else if(key=="backspace"){
          el.value = el.value.slice(0,-1);
        } else if(key==" "){
          el.value += " ";
        } else {
          el.value += String.fromCharCode(key);
        }
      }
    }
    

    Demo here

    Please note that you should run writeKey not onclick but onmousedown. Otherwise focus will be already moved from an input. Demo reflects that.

    Here is its html code:

    <div onmousedown="writeKey('a');return false">Click key</div>
    <input type="text" />
    <input type="text" />
    <input type="text" />
    

    Also, take a look at return false; after writeKey is called. It will prevent default browser action and clicking on a key you will not loose a focus from your input. Without it you will need to set focus on an element after each key press.