Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 207
Kailash PK Avatar asked Oct 19 '25 02:10

Kailash PK


2 Answers

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.

like image 101
Mukul Jain Avatar answered Oct 21 '25 16:10

Mukul Jain


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 + "-";
    }
})
like image 28
Matthew LeFevre Avatar answered Oct 21 '25 16:10

Matthew LeFevre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!