Search code examples
javascriptonkeyup

Keyup handler is not getting called for my input element


I am new to javascript, so this may seem like a trivial question. I am trying trying to write a javascript program that will insert dashes into a phone number, but I can't get my code to work. Nothing is happening when I use onkeyup.

Am I doing something wrong? So far, it seems like only onfocus is working for me.

function keyup() {
  var mystring;
  mystring.concat(document.getElementById('Phone').value, '-');
  document.getElementById('Phone').setAttribute('value', mystring);
}
<input type="text" id="Phone" name="Phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" onkeyup="keyup">

My editor has issues and is highlighting stuff. Is there an issue with single quotes double quotes? Are the returns in the lines alright? It appears ok when I view the source on Chrome version 66.


Solution

  • Based on what you said in your question, this is what you want:

    function keyup() {
      var mystring = document.getElementById('Phone').value;
      document.getElementById('Phone').value = mystring + "-";
    }
    <input type="text" id="Phone" name="Phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" oninput="keyup()" />

    • you need to put () after the keyup in onkeyup="keyup"
    • you were concating to undefined
    • you don't need to even use concat, just use the + operator
    • replace setAttribute("value", ...) with .value = .... See this answer for more info
    • use the input event instead of keyup. Otherwise, a - will be added for every key press

    Notice that this will put a - after every number. If you want something different, which you presumably do, clarify what you want in your question.