views:

203

answers:

3

I'm trying to find a reusable way to set focus from one text box to another upon enter using ASP.NET, but using client-side JavaScript to do so.

The only reason I mention this is to be done in ASP.NET, is due to the fact that client Id's of the controls that ASP.NET renders can be different than what was specified in the markup.

+2  A: 

Modified following code to get your goal.

    /***********************************************
    * Disable "Enter" key in Form script- By Nurul Fadilah([email protected])
    * This notice must stay intact for use
    * Visit http://www.dynamicdrive.com/ for full source code
    ***********************************************/

function handleEnter(field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                if (field == field.form.elements[i])
                break;
            i = (i + 1) % field.form.elements.length;
            field.form.elements[i].focus();
            return false;
        }
        else
            return true;
    }
Henry Gao
See my comment @Odge as TAB may be the better key to use, in which case you're just using enter as a tabindex replacement with this code. I'm assuming TAB won't work for BlueSam for some reason, so he may want to pass the id of the NEXT field rather than the current field in order to be explicit about navigation. Failing TAB and assuming these are plain single line text boxes, maybe down or up arrow? ENTER usually means "send my data" in data entry if you aren't in multi-line. Good catch on using enter inside a form and needing to redirect it.
Jim Leonardo
+1  A: 

You could try this.

function ChangeOnEnter (event, target) {
     if(event.keyCode === 13){
         document.getElementById(target).focus();
         return false;
     }
}

<input type="text" id="first" onKeyPress="ChangeOnEnter(event,'second')"/>
<input type="text" id="second"/>

Hope it's what you're looking for.

Oscar Kilhed
Deleted my post b/c it was redundant. The only thing I would recommend is not using ENTER... Assuming there's something that tabindex can't solve, I would still recommend using TAB as the "move to next" key as that is the UI convention. "Nice boring UIs for the adult in all of us" is the road to user friendly applications.
Jim Leonardo
A: 

You could make use of the tabindex html element property to allow users to through the fields. This is, in my opinion, a universal mechanism for moving through a form.

http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex

Kyle B.