Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.
Asked
Active
Viewed 1.7e+01k times
10 Answers
123
From http://www.codeave.com/javascript/code.asp?u_log=7004:
var input = document.getElementById('myTextInput');
input.focus();
input.select();
<input id="myTextInput" value="Hello world!" />

Ethan
- 4,295
- 4
- 25
- 44

John Millikin
- 197,344
- 39
- 212
- 226
-
3This works in Firefox but this will not select the text in Chrome or Edge. – Vincent Sep 09 '15 at 23:19
42
-
This only works in FireFox. In Chrome you can kind of fix this by adding "onmouseup='return false'" but that won't solve the problem in Edge, nor does it solve the problem if you are using the keyboard to navigate into the element. – Vincent Sep 09 '15 at 23:17
-
4Just tried it and works on Chrome as well (`Version 55.0.2883.95 (64-bit)`) – Wim Deblauwe Jan 19 '17 at 15:06
-
this works perfectly since my input were too many and I uses Class not ID – Salem Oct 26 '19 at 14:40
39
try this. this will work on both Firefox and chrome.
<input type="text" value="test" autofocus onfocus="this.select()">

Vivek ab
- 660
- 6
- 15
5
I found a very simple method that works well:
<input type="text" onclick="this.focus();this.select()">

pedalGeoff
- 747
- 1
- 8
- 15
5
In your input tag use autofocus like this
<input type="text" autofocus>
2
when using jquery...
html:
<input type='text' value='hello world' id='hello-world-input'>
jquery:
$(function() {
$('#hello-world-input').focus().select();
});

Sean M
- 1,990
- 20
- 16
-
If you're using jQuery, you can forgo `focus()` and just call `select()`. – Sinjai Jan 09 '19 at 21:26
0
var input = document.getElementById('myTextInput');
input.focus();
input.setSelectionRange( 6, 19 );
<input id="myTextInput" value="Hello default value world!" />
select particular text on textfield
Also you can use like
input.selectionStart = 6;
input.selectionEnd = 19;

paranjothi
- 103
- 6
0
Using the autofocus
attribute works well with text input and checkboxes.
<input type="text" name="foo" value="boo" autofocus="autofocus"> FooBoo
<input type="checkbox" name="foo" value="boo" autofocus="autofocus"> FooBoo

M. Ivanov
- 9
- 2
0
Let the input text field automatically get focus when the page loads:
<form action="/action_page.php">
<input type="text" id="fname" name="fname" autofocus>
<input type="submit">
</form>
Source : https://www.w3schools.com/tags/att_input_autofocus.asp

lifeae
- 1