javascript focus input

This page discusses - javascript focus input

javascript focus input

javascript focus input

        

JavaScript can be very useful while the user fills the form containing number of fields in the web page. You can automatically transfer the focus to any other input field in the page. It can be performed using focus() method on the html element. To understand how focus can be set to any input field, we have created the example below. It has two input fields to take name and address as input from the user and a submit button. This button calls the function setfocus() which checks whether user has entered some value to the input boxes one by one. If any one is empty then it floats an alert box indicating the user to fill some value and then sets the focus to that input element.

focusinput.html

<html>
<head>
<title>javascript focus input</title>
<script type="text/javascript">

function setfocus() {
if ( document.getElementById('name').value.length == 0) {
alert("Please enter your first name.");
document.getElementById('name').focus();
}

else if(document.getElementById('add').value.length == 0) {
alert("Please enter your address.");
document.getElementById('add').focus();
}
}

</script>
</head>
<body>
Name<input type="text" id="name"/><br>
Address<input type="text" id="add"/><br>
<input type="button" id="name" onClick="setfocus()" value="Submit" />

<br>
</body>
</html>

The above code displays the page as given below:

If you click Submit button without entering text into the Name field then it floats the alert box indicating you to enter some text into it.

Clicking the OK button on the alert box takes the focus to the name input field as shown below.

Enter some text like 'roseindia' in the name text box and click on Submit button. It shows you an alert box again informing you to enter the address. As you click on OK, focus reaches to the address input box automatically.