javascripthtml

Evt.which and Evt.keyCode deprecated and JavaScript Errors


Currently I have several scripts that take the numbers the user enters into a text field for a phone number and converts the number into the standard (123) 456-7890 format. When validating my script (Code Beautify) it's throwing errors such as evt.which and evt.keyCode are deprecated, document used before it was declined, etc.

I'm just wondering if there is a different way to do what I am trying to do that isn't deprecated and not give the same errors?

As the user types in the number into the field, it will force it to display it in (123) 456-7890 format in both the field itself and the output.

// Format the phone number as the user types it
document.getElementById('ContactPhone').addEventListener('keyup', function(evt) {
  var ContactPhoneVal = document.getElementById('ContactPhone');
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  ContactPhoneVal.value = phoneFormat(ContactPhoneVal.value);
});

// We need to manually format the phone number on page load
document.getElementById('ContactPhone').value = phoneFormat(document.getElementById('ContactPhone').value);

// A function to determine if the pressed key is an integer
function numberPressed(evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 36 || charCode > 40)) {
    return false;
  }
  return true;
}

// A function to format text to look like a phone number
function phoneFormat(input) {
  // Strip all characters from the input except digits
  input = input.replace(/\D/g, '');

  // Trim the remaining input to ten characters, to preserve phone number format
  input = input.substring(0, 10);

  // Based upon the length of the string, we add formatting as necessary
  var size = input.length;
  if (size === 0) {
    input = input;
  } else if (size < 4) {
    input = '(' + input;
  } else if (size < 7) {
    input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6);
  } else {
    input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + ' - ' + input.substring(6, 10);
  }
  return input;
}
<input type="text" id="ContactPhone" autocomplete="off">


Solution

  • Here is a more modern version using arrow functions and removing the inline handler. I wrapped the code in a load handler to allow the code to be placed anywhere in the document - inline or external.

    I am using event.key instead of which and keyCode

    window.addEventListener('load', () => { 
      const contactPhoneInput = document.getElementById('ContactPhone');
      if (!contactPhoneInput) return console.warn('ContactPhone element not found.');
    
      const ALLOWED_CONTROL_AND_ARROW_KEYS = [
    'Backspace', 'Tab', 'Enter', 'Delete',
    'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'
      ];
    
      const phoneFormat = (input) => {
    const cleaned = input.replace(/\D/g, '').slice(0, 10);
    if (cleaned.length === 0) return '';
    
    let formatted = `(${cleaned.slice(0, 3)}`;
    if (cleaned.length > 3) formatted += `) ${cleaned.slice(3, 6)}`;
    if (cleaned.length > 6) formatted += ` - ${cleaned.slice(6, 10)}`;
    
    return formatted;
      };
    
      const shouldAllowKey = (evt) => {
    const key = evt.key;
    const allowed = (key >= '0' && key <= '9') ||
                    ALLOWED_CONTROL_AND_ARROW_KEYS.includes(key) || 
                    evt.ctrlKey || evt.metaKey;
    return allowed;
      };
    
      contactPhoneInput.addEventListener('keydown', (e) => {
    if (!shouldAllowKey(e)) {
      e.preventDefault();
    }
      });
    
      contactPhoneInput.addEventListener('input', (e) => {
    e.target.value = phoneFormat(e.target.value);
      });
    
      if (contactPhoneInput.value) {
    contactPhoneInput.value = phoneFormat(contactPhoneInput.value);
      }
    });
    <input type="text" id="ContactPhone" autocomplete="off">