views:

83

answers:

2

Consider the following:

<form runat="server">
    <div>
        <asp:TextBox runat="server" ID="tb1" />
        <asp:Button runat="server" ID="b1" OnClick="b1_Click" />
    </div>

    <div>
        <asp:TextBox runat="server" ID="tb2" />
        <asp:Button runat="server" ID="b2" OnClick="b2_Click" />
    </div>

    <div>
        <asp:TextBox runat="server" ID="tb3" />
        <asp:Button runat="server" ID="b3" OnClick="b3_Click" />
    </div>
</form>

Each TextBox has an associated Button. I want to be able to switch the focus on each of these Button controls, so that when I place my cursor in the 2nd textbox (tb2) and press Enter, the associated button (b2) gets clicked and the associated OnClick event gets fired.

I've got a few ideas myself, but I'd like you guys' feedback/lessons-learned before I start potentially wasting time on implementing a broken solution.

NOTE:

  • Using the HTML fieldset element is not an option--Some of the interfaces are very complex.
  • There can be multiple inputs associated with one button.
+4  A: 

You could trap the keydown event on the Textbox and then fire the button's callback javascript if it's the enter key. You can get the callback reference using ClientScriptManager.GetPostBackEventReference

Alternatively you could wrap every textbox in it's own Panel, which exposes a DefaultButton property.

Pike65
Didn't know you could set the DefaultButton on a Panel, nice answer
danrichardson
+1 for DefaultButton. Just don't set the GroupingText, otherwise you'll end up with a <fieldset> and not a <div>
Zhaph - Ben Duguid
Setting the DefaultButton property is sort of the same thing as using a fieldset. Which I can't implement due to the complexity of the interfaces. I had __doPostback() in mind as well. Perhaps extending a Button control and implementing a property which I can then pick up onsubmit. Hmm :)
roosteronacid
<asp:Panel runat="server" DefaultButton=""> did the trick. Thanks Pike65.
roosteronacid
+2  A: 

Well you could do a nice simple route using jQuery if you are using it.

Simply doing the following might work nicely:

<script language="javascript" type="text/javascript">
  jQuery(function(){ 
     jQuery('input').keydown(function(e){
      if (e.keyCode == 13) {
        jQuery(this).next().trigger('click');
        return false;
      }
 });
  });
</script>

And then code side you would have the relevant event handler triggered, or just simply see which button was clicked by querying the sender object id

danrichardson
Looks good. But what if you are writing in a textfield element? :)
roosteronacid
jQuery('input, textarea') :P
danrichardson
Aye, but then you'd fire the click-event on a button, when you want to do a line-break in a textarea :)
roosteronacid
Touché! Though this would also be a problem then in any solution that was used! :)
danrichardson
Touché.. Hehe ;)
roosteronacid