How to focus input and deselect text inside it

Currently, I want to focus the first input element without selecting the text of the set value inside the input element. How can I focus my input element and then deselect the text inside it? My current jQuery focus is as follows.

$(document).ready(function() { $("input[name='title']").focus(); }); 
+6
source share
5 answers
 $(document).ready(function() { $("input[name='title']").focus(); $("input[name='title']").val($("input[name='title']").val()); }); 
+7
source

You can use the selectionStart and selectionEnd properties:

 $(document).ready(function() { $("input[name='title']").each(function(){ this.focus(); this.selectionEnd = this.selectionStart; }); }); 
+6
source

This is based on Danilo Valente's answer above. I found that in Chrome I had to use a slight delay before calling this.selectionEnd = this.selectionStart , otherwise the input text will remain selected:

This works for me in Chrome, Firefox, Safari, and IE (IE 10 tested)

 $("input").focus(function() { var input = this; setTimeout(function() { input.selectionStart = input.selectionEnd; }, 1); }); 

Here is a demo: http://jsfiddle.net/rangfu/300ah0ax/2/

+2
source
 $("input[name='title']").focus(function() { var elem = $(this); elem.val(elem.val()); }); 
0
source

His ugly purchase can help you

Jsfiddle

Highlights: Overwrite what already exists ...

 $(document).ready(function() { $('#t1').focus(); $('#t1').val($('#t1').val()); }); ​ 
-2
source

Source: https://habr.com/ru/post/920086/


All Articles