Skip to content Skip to sidebar Skip to footer

How To Add Dashes Into A Number Input Field While Entering The Number?

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 tr

Solution 1:

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);
    });
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype='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.

Solution 2:

Vanilla javascript rendition partially inspired by Naman's code with a few more features like deleting and backspacing support.

HTML:

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

Solution 3:

Give an ID of your textbox and no need of blur function just write this in your document.ready function. Your HTML line:

<inputtype='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() + "-");
                    }
                    elseif ($(this).val().length == 9) {
                        $(this).val($(this).val() + "-");
                    }
                    elseif ($(this).val().length == 14) {
                        $(this).val($(this).val() + "-");
                    }
                });
});

hope it will helpful to you.

Post a Comment for "How To Add Dashes Into A Number Input Field While Entering The Number?"