Search code examples
javascriptjqueryfunctionkeyup

Getting function to run as user types


I have a phone number input that I am trying to get the dashes to appear in the number as the user types.

I am wanting the number to appear as 555-555-5555.

The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.

Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?

$('#phone').keyup(function() {
		$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <label class="contact-label">Phone Number:</label>
  <input type="tel" class="contact_input" name="phone" id="phone">
</div>


Solution

  • I modified your code slightly to produce something that I think is a little easier to read, but still does the job.

    I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:

    --UPDATE--

    After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:

    First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.

    I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.

    let formatFlag = false;
    
    $(function(){
    
      $('#phone').keyup(function(evt) {
          
          let modifiedValue = $(this).val().replace(/-/g, "");
          
          if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
            
            //Checks whether the user backspaced to a hyphen index
            if(modifiedValue.length === 3 || modifiedValue.length === 6) { 
            
              //Checks whether there is already a hyphen
              if($(this).val().charAt($(this).val().length - 1) !== '-') {
              
                formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
                
              } else {         
              
                return false; //Hyphen already present, no formatting necessary
                
              }
              
            } else {
            
              formatFlag = false;
              
            }
            
            return false; //Return if backspace or delete is pressed to avoid awkward formatting
          }
          
          if(!!formatFlag) {
          
            // This re-formats the number after the formatFlag has been set, 
            // appending a hyphen to the second last position in the string
            $(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' + 
            $(this).val().slice($(this).val().length - 1));
            
            formatFlag = false; //Reset the formatFlag
          }
          
          if(modifiedValue.length % 3 == 0) {
          
            if(modifiedValue.length === 0 || modifiedValue.length >= 9){
            
              return false;
              
            } else {
            
              $(this).val($(this).val() + '-');
              return;
              
            }
          
          }
    
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div>
      <label class="contact-label">Phone Number:</label>
      <input type="tel" class="contact_input" name="phone" id="phone" />
    </div>