iOS and Android [type=number] setSelectionRange vs. select

1k views Asked by At

I am attempting to highlight the text of an input[type=number] by clicking it. I originally tried select() which worked for Chrome (Android), but it did not work for Safari (iOS).

So I found a piece of code which recommended I try setSelectionRange(0, nativeEl.value.length);

This worked well for iOS! However, for Chrome, it crashes:

Uncaught DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection.

So one method works for one platform, not the other, and vice versa.

My question is, what is the best way to determine the best platform differences without browser sniffing? setSelectionRange is present on both Chrome and Safari instances of input. Thus, checking for that property is redundant.

The best code I have come up with so far is as follows:

let nativeEl: HTMLInputElement = this.el.nativeElement.querySelector('input');

if (nativeEl) {
  if (nativeEl.setSelectionRange) {
    // select the text from start to end
    try {
      nativeEl.setSelectionRange(0, nativeEl.value.length);
    } catch (e) {
      nativeEl.select();
    }
  }

  nativeEl.select();
}

But it seems an antipattern to rely on a catch statement. Is there a better way to do this?

0

There are 0 answers