0

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.

pushkin
  • 9,575
  • 15
  • 51
  • 95
bandguyz24
  • 13
  • 1

3 Answers3

0

You forgot the parenthesis on 'onkeyup' attribute.

Plus you have to declare a string value to variable 'mystring' before calling the 'concat' method from it.

Something like:

<script>
  function keyup() {
  console.log("keyup!!")
    var mystring = "";
    mystring.concat(document.getElementById('Phone').value, '-');
    document.getElementById('Phone').setAttribute('value', mystring);
  }
</script>

<input type="text" id="Phone" name="Phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" onkeyup="keyup()">
Jair
  • 96
  • 4
  • I tried using this code and nothing still happens ..do i need the script above the input? i currently have at the bottom of the body. where can I see console log? – bandguyz24 May 30 '18 at 20:40
0

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="###-###-####" onkeyup="keyup()">
Eliuber
  • 48
  • 1
  • 8
0

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.

pushkin
  • 9,575
  • 15
  • 51
  • 95