How to Set the Focus & Select All in JavaScript
- 1). Create a new HTML document using an editor or the Notepad. Add a form to the document with an input field that you want to focus and select all. Name the form and the input field to make it easy to refer to them using JavaScript. For example, type:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Focus and Select All</title>
</head>
<body>
<form name="frm"><input type="text" name="txt" /><br/><input type="submit" name="submit" value="Submit" /></form>
</body>
</html> - 2). Create a JavaScript function between the <head> tags of the HTML document. Set the focus of the form to the HTML field and select all the text in the field. Reference the field using the name assigned in the HTML form. For example, type:
<script type="text/javascript">
function focusSelect() {
var fld = document.frm.txt;
fld.focus();
fld.select();
}
</script> - 3). Modify the HTML form to call the JavaScript function when focus is taken off the input field. Change the input statement on the HTML form. For example, type:
<input type="text" name="txt" onblur="focusSelect()" />