1

In essence, the basic stuff you find when looking for selecting contents on click works, but for me it doesn't work reliably. When I click the input element the first time, all text is selected as it should. If I click off of it, and then click it again, it selects the text, but then immediately de-selects it and shows a cursor where I clicked. This is a repeating pattern, i.e. it works once, then doesn't work once, etc..

I have tried preventing anything and everything with preventDefault and stopImmediatePropagation, I tried returning false in onMouseUp, but I can't get rid of this behavior. What's causing the deselection on the n*2-nd click, and how can I prevent it?


Edit in reply to comments:

I didn't include a snippet since, well, there is hardly anything to show:

<input type="text" value="-:--" onFocus={((e) => e.target.select())} />

That's all, and that's causing me issues. In the meantime though, I started looking at alternative methods of handling this, and I stumbled into something that may be relevant: the text doesn't get de-selected if I click off of the input window. If I click on the input and call document.getSelection().toString() in the console, it prints -:-- as expected. However, if I then click somewhere else on the page, which deselects the input field, and call document.getSelection().toString() again, it still prints -:--. This gave me enough info to figure out what the issue is and how to fix it, so I'll add my own answer.

Timmiej93
  • 1,328
  • 1
  • 16
  • 35

2 Answers2

1

TL;DR:
Either call document.getSelection().empty() in onBlur/onFocusOut, or make sure you don't have user-select: none set on everything.

Explanation
It turns out the issues I was having were caused by having user-select: none set on the entire body, which prevented the actual deselection of the text in the input field. Although the text did look like it was deselected (the blue highlighting disappeared), calling document.getSelection().toString() showed that the text was still selected.

Since setting user-select: none on the body is pretty agressive, I suspect most people would recommend you don't do that, and be more specific. If you still want to keep it on the body though, calling document.getSelection().empty() (which deselects your selection) in an onBlur/onFocusOut event also works fine.

Timmiej93
  • 1,328
  • 1
  • 16
  • 35
0
 onClick="this.setSelectionRange(0, this.value.length)"
OmidDarvishi
  • 558
  • 4
  • 8