How to Set the Focus & Select All in JavaScript
JavaScript allows you to directly reference the values and properties of HTML elements such as input fields. To make referencing the input fields easy, you should name each input field in the HTML form. JavaScript has a method called "focus" that allows you to set the focus to a particular field on an HTML input form. It also has a method called "select" that allows you to select the text in an HTML input field.
Instructions
-
-
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" width="30" /><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" width="30" onblur="focusSelect()" />
-
1