Monday, September 13, 2010

How to shift focus to next textbox on a ASP.Net web page

I encountered this situation when one of my co-workers was testing a web page I had been helping to develop. After entering text in a textbox on the page and hitting the enter key, the control was getting passed down randomly to any next control on the page, which would be unfriendly and inconvenient to the user.

I searched various posts on the web to find the best solution to this situation and the one that worked best for me was provided here :

In this article Suprotim Agarwal shows how to shift focus to the next TextBox control using JQuery. I used the script part of the code on my webpage :
<script type="text/javascript">
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
script>

When I ran the application, the TextBoxes on the page received focus in the order they were expected to.


No comments:

Post a Comment