Changing input field value with JavaScript

Hi there,

I’m trying to change the value of input fields that are part of the sign-up form. I added some code that changes the value whenever the field input changes (using the ‘input’ event listener). This works, however, as soon as I click away from the field, it deletes the value completely. Here’s what I have:

//   Wait for specific element to be loaded
waitForElm('#user-accounts1 div[mappedto="First Name"] input').then((elm) => {
        let firstNameInput = document.querySelector('#user-accounts1 div[mappedto="First Name"] input');
        firstNameInput.addEventListener('input', function() {
            let capitalized = firstNameInput.value.charAt(0).toUpperCase() + firstNameInput.value.slice(1);
            firstNameInput.value = capitalized;
        });
      });

I also tried using the method described here, but this didn’t work for me either.

How can I change the values of the input fields (or hidden fields)? Is there a specific event I could listen for before the form gets submitted that would give me a chance to change the value before submission? I have other use cases other than capitalising the first word, the main thing I need is to set/change the value of the fields before submission in a way that then submits the value I set without changing it back/deleting it.

Thank you!

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