简体   繁体   中英

how to auto select an input field and the text in it on page load

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.

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!" />

在您的输入标签中,放置以下内容:

onFocus="this.select()"

try this. this will work on both Firefox and chrome.

<input type="text" value="test" autofocus="autofocus" onfocus="this.select()">

To do it on page load:

 window.onload = function () { var input = document.getElementById('myTextInput'); input.focus(); input.select(); }
 <input id="myTextInput" value="Hello world!" />

我发现了一个非常简单的方法,效果很好:

<input type="text" onclick="this.focus();this.select()">

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/

 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;

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

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

在您的输入标签中,像这样使用自动对焦

<input type="text" autofocus>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM