Four text boxes are in a JSP page. After entering first text box, when I press Tab, the focus moves to the second text box. Similarly the focus will be on 3rd and 4th text box after pressing Tab repeatedly.
<input type="text" id="textbox1"/>
<input type="text" id="textbox2"/>
<input type="text" id="textbox3"/>
<input type="text" id="textbox4"/>
If I move from the first to the third text box without filling the second text box, then I want to have an alert come as “2nd text box cannot be empty”. Similarly after entering data on first, second if I am moving to the fourth text box without filling the third text box, then I want an alert as “3rd text box cannot be empty”. And after the alert the focus must be on that empty text box again, the focus must not move further. How can I do this?
You’ve tagged the question with jQuery so I’ll give you a jQuery solution. You may want to make the selector a bit more specific, depending on your HTML:
This binds an event handler to the
blurevent of the elements (which fires when the field loses focus, be it through pressing tab, clicking elsewhere or any other method of changing focus). The event handler checks whether the field has a value, and if not it alerts a message, using the jQueryindexmethod to get the index of the element relative to its siblings.Here’s a working example.