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.
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()" />
()
after the keyup
in onkeyup="keyup"
concat
ing to undefined
concat
, just use the +
operatorsetAttribute("value", ...)
with .value = ...
. See this answer for more infoinput
event instead of keyup
. Otherwise, a -
will be added for every key pressNotice that this will put a -
after every number. If you want something different, which you presumably do, clarify what you want in your question.