81

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.

derick
  • 1,110
  • 2
  • 12
  • 13

10 Answers10

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
42

In your input tag, place the following:

onFocus="this.select()"
sth
  • 222,467
  • 53
  • 283
  • 367
dvo
  • 437
  • 4
  • 2
  • 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
  • 4
    Just 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
17

To do it on page load:

window.onload = function () {
  var input = document.getElementById('myTextInput');
  input.focus();
  input.select();
}
<input id="myTextInput" value="Hello world!" />
YakovL
  • 7,557
  • 12
  • 62
  • 102
roenving
  • 2,560
  • 14
  • 14
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();
});

example: https://jsfiddle.net/seanmcmills/xmh4e0d4/

Sean M
  • 1,990
  • 20
  • 16
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