ASP.NET - Default button when user hits [Return]

I need a simple way to make a particular (image)button on a web form fire when the user presses the return key, please.
 
LVL 2
sumo_the_catAsked:
Who is Participating?
 
dfiala13Commented:
Sure it will work with imagebuttons.

And remember its not Java, its Javascript, which is just a handy way to deal with client-side events on an HTML page.  ASP.NET makes extensive use of it for the validation controls and most third party custom controls are loaded with it.  So time to get unscared, because if you want to get the most out of ASP.NET (or any web development tool) you are going to have to at least get comfortable with Javascript.  Otherwise your developing will be severely handicapped.

We'll skip the script regsitering for now and do it the brute force way...

Put this in the HTML of your page, somewhere between the header tags...

<SCRIPT language=""javascript"">

<!--

function fnTrapKD(btn, event){

 if (document.all){

  if (event.keyCode == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if (document.getElementById){

  if (event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if(document.layers){

  if(event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

}

// -->

</SCRIPT>

All this does is capture the enter key.  All the if-else stuff is because not all browsers are created equal they all have different ways of identifying elements (which is a royal pain).

Now, add this method to your code-behind or your VB script.  This will add an onkeydown trap to every text control you send to it...

Private Sub SetDefaultButton( txt as TextBox, defaultButton as ImageButton )
 txt.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");


End sub

Finally, in your Page_load event handler, add a call to the method for each text box you have. It will set the default button to use for every textbox.  You can use the same button for each textbox or different ones.

SetDefaultButton(TextBox2, Button2)

That's all there is to it. Hit the enterkey and submit.

0
 
Fahad MukhtarDistinguished EngineerCommented:
Source :
http://www.utmag.com/September2003/Page3.asp



private void Page_Load(object sender,
    System.EventArgs e)
{
   // This causes the page to associate Enter
   // key with btnSearch click.
   Page.RegisterHiddenField( "__EVENTTARGET",
       "btnSearch" );
}

Note
0
 
sumo_the_catAuthor Commented:
In VB.NET, this should work, right?

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Set default button to btnSearch.
        Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")

    End Sub

I doesn't, though. Any ideas why? (there is certainly more than one textbox on the form, although one of them is yellow for no reason whatsoever.)
Thanks,
Pete.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
dfiala13Commented:
>> although one of them is yellow for no reason whatsoever
Do you have a Google toolbar?  if so Check the Google Toolbar Options and turn off AutoFill. The toolbar checks for fields that look like likely candidates for autofill and highlights them.  
0
 
sumo_the_catAuthor Commented:
Clever! Nice one dfiala13. You can have some extra points! I would have wasted days on that, in all likelihood. But do you know why the reason why the above isn't working?
0
 
sumo_the_catAuthor Commented:
On a similar (completely unrelated!) note, do you how to get rid of all the double spacing on my web forms? It's really annoying, but I want to use flow layout. I'll post extra points outside this q.
0
 
dfiala13Commented:
>> But do you know why the reason why the above isn't working?
Good question.  I'll see if I can see what's what.

>>double spacing on my web forms
What do you mean?  I use flowlayout all the time.
0
 
sumo_the_catAuthor Commented:
Well, when I press enter to start a new line, I get large gaps in between each line.
0
 
dfiala13Commented:
OK, Though it would be nice if were that easy
Reason  Page.RegisterHiddenField( "__EVENTTARGET",
       "btnSearch" );
 won't work because

the script has no idea what to do with it.  If you look at your html source after the page renders you won't see anything referencing it (unless perhaps you have some validators turned on -- but even then it won't work because it will get overwritten in the validation script).

No, you need to do some keycapture in javascript and have it set the event target and tnen call the submit when the enter key is pressed.
0
 
dfiala13Commented:
The VS designer is throwing <p> tags around each line.  You can either change the default style of the <p> or simply remove them or don't use the designer for entering long text blocks.
0
 
sumo_the_catAuthor Commented:
Don't know Jscript... This must be a common requirement - surely there's a way to do it?

This should be a different thread, but i guess it's "line-height" that i need to change. But to what value? visual studio is only suggesting 'Normal'.
0
 
dfiala13Commented:
>>This must be a common requirement - surely there's a way to do it?
There is -- Javascript.  This is all client-side behavior.

You capture the enter key down event and call the form submit. Here's an example...

http://dotnetjunkies.com/WebLog/darrell.norton/archive/2004/03/03/8374.aspx

You can also attempt to set the tab order.  First button in the tab order "usually" gets the default submit

you can change the line height to a value in pixels line-height: 15px.  
0
 
sumo_the_catAuthor Commented:
I've had a look at that URL before, but left feeling confused. Will it work with imagebuttons? Can you tell me exactly what to do to get it to work in VS.NET with VB.NET? Java confuses the heck out of me, being an MS Access programmer by heart.
0
 
sumo_the_catAuthor Commented:
That works perfectly. Some points for you my friend:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20946265.html

Is there a way to capture "form"-wide events? I'd like to have an application-wide toolbar which uses the function keys as shortcuts. Is this possible, and could it be incorporated with this solution?

I've ballsed up my <P> tags though! I'll have to start again.
0
 
davisg090767Commented:
I might be wrong here but I think you can press ctrl-M or shift-M instead of the return key in Flow layout which inserts <br> instead of <p>, Give it a try I'm sure that worked for me.
0
 
dfiala13Commented:
>>Is there a way to capture "form"-wide events?
You can try to add a onkeydown trap to the body element...

<body onkeydown="return MyTrap(event);">

and add a script similar to the one above to deal with it.  Of course to really make it useful, you'd want to put it in a user control and have it alter the body element on whatever page it was put on.
0
 
sumo_the_catAuthor Commented:
davisg090767: that just inserts <P>s, but thanks for telling me about the <br> tag - that gives me a new line with no space.

I'm going to need some help with all this formatting business, especially tags. VB.NET is fine, but I'm finding this web stuff much more fiddly than I'd expected..!

I can't work out how to change the double line-spacing in between the <P></P> tags. I don't want double, but single isn't much use either when a small gap is needed.

I will post another question though.

Thanks for all the help. dfiala13, you know your stuff.
0
 
susanh02Commented:
Thanks for the solution!  It was really helpful.

If you know you want the same default button behavior for all TextBox controls in your page, you can iterate over the Controls.  This takes less typing than adding it manually for all text boxes.  (C#)

            public void SetDefaultButtons( Button button )
            {
                  foreach ( Control control in this.Controls )
                  {
                        if ( control is TextBox )
                        {
                              SetDefaultButton((TextBox)control, button);
                        }
                  }
            }

0
 
groggyjavaCommented:
holding down the shift key in design mode inserts a line-break and not a new paragraph
it works almost all microsoft products, macromedia and a bunch of others, too.
0
 
groggyjavaCommented:
correction: holding down the shift key WHILE YOU HIT ENTER inserts ...
0
 
steveexmetCommented:
Hi, in relation to the posting by "dfiala13" for this solution mine doesnt work, when im in my textbox i still get a  server roundtrip rather than the javascript function been invoked ?.  i have looked at the source after the page as rendered and the onkeydown attribute has been added suceesfully from C# - onkeydown="fnTrapKD(Datechange)" - so this is ok, but in this function all i have now is an alert statement and even that doesnt get triggered, its like the page/browser is overriding the added attribute. any ideas
steve
0
 
jisarp3Commented:
If you ahve a panel on the page it has a DefaultButton you can set


0
 
amkbaileyCommented:
This is the simple way to do this: In your VB.NET code just add this code below to your Page_Load subroutine.

Me.frm.DefaultButton = Me.but.ID

Where 'frm' is the name of your form in the your ASPx page and 'but' is the name of your button.
0
 
sunultrasparcCommented:
For other newbs  like me if your not working with an imagebutton make sure you change your routine to the correct button type.

example below

Private Sub SetDefaultButton( txt as TextBox, defaultButton as Button )
 txt.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");
End sub

Worked Great, Thanks for your hard work!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.