7 September 2004
ASP.NET Focus Issue
Posted by Mikhail Esteves under: C#; Tips .
Let’s say you have one User Control and a Contact Us form. The User Control contains a small Login page and the Contact Us form the usual lot of Name, Email, Address and other controls.
Now, when the focus is in the control and the user presses Enter, the main form is submitted. Or the other way around. How do we get over this issue? I usually avoid this by using the onFocus event and a little bit of JavaScript.
In the textboxes of the login control, let’s add onFocus=“javascript:setSubmit(1);” and to all the textboxes of the Contact form, lets add the attribute onFocus=“javascript:setSubmit(2);”. For any textareas that you have in your Contact form, use setSubmit(3) instead. This ensures that the user can safely use the Enter key in the textarea without submitting the form half-way through!
Now in the header include or the common JS file or wherever, add the following Javascript:
var toSubmit = "btnSubmit";function setSubmit(x){ if (x==1){ toSubmit = 'btnLogin'; }else if (x==2){ toSubmit = 'btnSubmit'; }else{ toSubmit = 'none'; } } function goSubmit(){ if (toSubmit != 'none') document.getElementById(toSubmit).click(); }
Note that btnLogin is the ID of the login button in the login control and btnSubmit the ID of the submit button on the Contact form.
That’s about it. Now the only little thing left for you to do is to add the following attribute to the body tag of the page:
onkeydown="if(event.keyCode == 13){goSubmit();}"
Your problem is then solved. An enter in the login control will trigger btnLogins server routine. Same with the other one.
However, if your problem is simpler than this — say, like Google, you have two buttons and you want the enter key to submit one of them, you can do so by doing the following on Page_Load of the form:
private void Page_Load(object sender, System.EventArgs e)
{
Page.RegisterHiddenField("__EVENTTARGET", "btnFeelingLucky");
}
Now, an enter key will trigger btnFeelingLucky instead of the first button there. The same thing can be done using an onKeyDown attribute in the body tag too. Example:
onkeydown="if(event.keyCode == 13){document.getElementById('btnFeelingLucky').click();}"
That’s about it!
3 Comments so far...
Steve Dz Says:
20 May 2005 at 8:43 pm.
Thanks for posting this. It needs a ‘return false;’ after the .click(); and before the } but it works fine.
Mikhail Esteves Says:
17 September 2005 at 4:56 pm.
@Rik: Doesn’t work. Your first form submits fine but the second one bombs.