Search code examples
internet-explorerangular7uppercase

Prevent cursor from moving to end of the input box when user makes edits, in IE browser


In my anuglar 7 application, in all text input fields, I am including a method that changes the value of whatever text the user types, to uppercase. In IE browsers, when the user makes an edit to the text they enter, the cursor automatically moves to the end of the input box instead of staying in place.

I suspect the method that is causing the issue is this:

oninput="this.value = this.value.toUpperCase()"

I do not have this issue in chrome browsers. What can I do to prevent this from happening in IE browsers?

My html code for the input field:

          <input
            type="text"
            class="form-control col-lg-7"
            id="primary-email"
            formControlName="primaryEmail"
            pattern="[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?"
            placeholder="[email protected]"
            required
            [ngClass]="{ 'is-invalid': submitted && f['primaryEmail'].errors }"
            [(ngModel)]="primaryEmail"
            oninput="this.value = this.value.toUpperCase()"
          />

Solution

  • As suspected, the issue was coming from

    oninput="this.value = this.value.toUpperCase()"
    

    The change I made to resolve this (after some googling) was to create a method in my TS file:

    makeUpperCase(e) {
      const cursorStart = e.target.selectionStart;
      const cursorEnd = e.target.selectionEnd;
      e.target.value = e.target.value.toUpperCase();
      e.target.setSelectionRange(cursorStart, cursorEnd);
    }
    

    Then in the HTML file, replace the problematic line with this:

    (input)="makeUpperCase($event)"
    

    Hopefully this helps anyone else running into a similar issue with IE.