Home:ALL Converter>Delete Button Won't Work Within SSN Input Field

Delete Button Won't Work Within SSN Input Field

Ask Time:2021-09-22T05:27:50         Author:Jon

Json Formatter

I am implementing a react component that formats a 9-digit number as a social security number in the format: xxx-xx-xxxx.

Unfortunately, I'm not able to select all (ctrl + a) and delete the ssn, probably due to my "keyup" function in the handleSSN() click handler. The "value" attribute of the Input component takes the nine digit number that the user inputs, and the formatSSN() function formats the number to appear as "xxx-xx-xxxx" in the input field. When a user tries to select all and delete what they have input in the field, the highlighted content will simply become un-highlighted when the user lifts the key up. Is there a way to accommodate for the "ctrl + a" behavior in this handler?

This functionality is heavily based on: http://jsfiddle.net/hughdidit/Y5SK6/ , which has the same issue of not being able to "ctrl+ a" the input box and delete the content. Any insight is greatly appreciated

<FormLabel clear="both" float="left">
  Social Security Number:
  border="1px solid #E2E8F0"
  placeholder="Text here"
  onChange={(e) => handleChangeSSN(e.target)}
  onBlur={(e) => handleChangeSSN(e.target)}}

formatSSN function (this doesn't have to do with the problem at hand, but is how the ssn is displayed in the input when the component loads, if an ssn is already in the database):

export const formatSocialSecurity = (val) => {
  val = val && val.replace(/\D/g, '');
  val = val && val.replace(/^(\d{3})/, '$1-');
  val = val && val.replace(/-(\d{2})/, '-$1-');
  val = val && val.replace(/(\d)-(\d{4}).*/, '$1-$2');
  return val;

The handleSSN() click handler function saves the value to the state (not shown below) after doing some validations itself:

 const handleChangeSsn = ({ value }) => {
    var keyCode = value.which || value.keyCode || 0;
      .addEventListener('keyup', function (event) {
        let val = this.value.replace(/\D/g, '');
        let newVal = '';
        if (val.length > 4) {
          this.value = val;
        if (val.length > 3 && val.length < 6) {
          newVal += val.substr(0, 3) + '-';
          val = val.substr(3);
        if (val.length > 5) {
          newVal += val.substr(0, 3) + '-';
          newVal += val.substr(3, 2) + '-';
          val = val.substr(5);
        newVal += val;
        this.value = newVal;

Author:Jon,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275750/delete-button-wont-work-within-ssn-input-field