Changing input field value with JavaScript

Hello,
here is the code to replace

<script>
function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

// Your wait for element logic here
waitForElm('#user-accounts1 div[mappedto="First Name"] input').then((elm) => {
  const capitalizeAndDispatch = function(e) {
    // Remove the event listener to prevent infinite loop
    elm.removeEventListener('input', capitalizeAndDispatch);

    // Capitalize value
    let capitalized = e.target.value.charAt(0).toUpperCase() + e.target.value.slice(1);

    // Update the value using the native setter
    setNativeValue(elm, capitalized);

    // Dispatch the React-friendly 'input' event
    elm.dispatchEvent(new Event('input', { bubbles: true }));

    // Re-attach the event listener
    elm.addEventListener('input', capitalizeAndDispatch);
  };

  elm.addEventListener('input', capitalizeAndDispatch);
});
</script>
2 Likes