3

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?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Kailash PK
  • 61
  • 1
  • 2
  • 13

3 Answers3

2

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.

Mukul Jain
  • 1,121
  • 11
  • 24
1

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 + "-";
    }
})
-1

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.

Naman Upadhyay
  • 531
  • 6
  • 12
  • 1
    This won't work if the user decides to modify early parts (like they typed it all out and realized they missed the second number). They also didn't say anything about jQuery, so I think a vanilla solution would be preferred. – lewisjb Feb 11 '17 at 06:38
  • It is working.But when I try to delete a digit in the middle it's getting messy.Can we do anything about that? – Kailash PK Feb 11 '17 at 06:43
  • And one more thing the max length attribute of the field is being taken in another sense there.The hyphens get also counted as a charechtor. The hyphens should be excluded in max length. – Kailash PK Feb 11 '17 at 06:50
  • For the length you can count it with hyphens and set it to your textbox maxlength like instead of 12 set it to 19. – Naman Upadhyay Feb 11 '17 at 06:54
  • Okay about deleting whatever element you want to delete go at that position using Arrow Key(<-- or -->) and then you can change that element as this is way and it works properly as if you don't want use of Masking and you want to use this code. if you ok with this then can you please upvote this and Mark As Answer. – Naman Upadhyay Feb 11 '17 at 10:51