Reputation: 71
I am trying to use java script to insert dashes into a html number field at every 4th
digit while entering.I did this in on-blur instead of on-key-press,on-key-up etc.But when I tried to change the function to on-key-press/on-key-up
events it is not giving the expected results.
This is the code which I used.
<html>
<head>
<script>
function addDashes(f)
{
f.value = f.value.slice(0,4)+"-"+f.value.slice(4,8)+"-"+f.value.slice(8,12);
}
</script>
</head>
<body>
Phone: <input type='text' name='phone' onblur='addDashes(this)' maxlength='12'><BR>
</body>
</html>
I am a beginner in 'JavaScript'. Where am I doing wrong?
Upvotes: 4
Views: 15975
Reputation: 21
Vanilla javascript rendition partially inspired by Naman's code with a few more features like deleting and backspacing support.
HTML:
<input type="tel" id="phone">
Vanilla JS:
const phone = document.getElementById('phone');
phone.addEventListener("keydown", (e) => {
if(e.key === "Backspace" || e.key === "Delete") return;
if(e.target.value.length === 4) {
phone.value = phone.value + "-";
}
if(e.target.value.length === 9)
phone.value = phone.value + "-";
}
if(e.target.value.length === 14) {
phone.value = phone.value + "-";
}
})
Upvotes: 2
Reputation: 1175
This will work. It also supports 'deletion' of number.
However, I would suggest you using masking
$(document).ready(function () {
$("#txtPhoneNo").keyup(function (e) {
if($(this).val().length === 14) return;
if(e.keyCode === 8 || e.keyCode === 37 || e.keyCode === 39) return;
let newStr = '';
let groups = $(this).val().split('-');
for(let i in groups) {
if (groups[i].length % 4 === 0) {
newStr += groups[i] + "-"
} else {
newStr += groups[i];
}
}
$(this).val(newStr);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="txtPhoneNo" name='phone' maxlength='14'><BR>
If you want a snippet of this using masking, let me know, I'll be more than happy to help.
Upvotes: 2
Reputation: 537
Give an ID of your textbox and no need of blur function just write this in your document.ready function. Your HTML line:
<input type='text' id="txtPhoneNo" name='phone' maxlength='12'><BR>
Your Jquery line:
$(document).ready(function () {
$("#txtPhoneNo").keyup(function () {
if ($(this).val().length == 4) {
$(this).val($(this).val() + "-");
}
else if ($(this).val().length == 9) {
$(this).val($(this).val() + "-");
}
else if ($(this).val().length == 14) {
$(this).val($(this).val() + "-");
}
});
});
hope it will helpful to you.
Upvotes: -1