5 Text box, 2 buttons. How to assign a textBox to a button?

I want to give my users the opportunity to use a text field and press Enter. The problem is that I have 5 text fields and 2 options. 3 belong to one button and 2 text fields to another. How can I call a specific button according to the text box the user was in when he presses Enter?

+5
source share
3 answers

I did this myself, where I had a page with two different registration formats for different types of users. What I did was split these two forms into my own ASP Panel and the panel setting DefaultButton, depending on what I wanted. Thus, when they finished typing in the form and pressed the enter key, he would send the correct button.

An example :

<asp:Panel id="panel1" DefaultButton="button1">
    <asp:textbox id="textbox1"/>
    <asp:textbox id="textbox2"/>
    <asp:buton id="button1"/>
</asp:panel>

<asp:panel id="panel2" DefaultButton="button2">
    <asp:textbox id="textbox3"/>
    <asp:textbox id="textbox4"/>
    <asp:button id="button2"/>
</asp:panel>

EDIT : Another method on how to do this by assigning the OnKeyPress property to your text fields. THIS IS A SEPARATE DECISION THAT I DESCRIBED IN TOP

An example :

function clickButton(e, buttonid){
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonid);
    if (bt){
        if (evt.keyCode == 13){
            bt.click();
            return false;
        }
    }
}

//code behind
TextBox1.Attributes.Add("onkeypress",
    "return clickButton(event,'" + Button1.ClientID + "')");

The following code is created in the code:

<input name="TextBox1" type="text" id="TextBox1" onkeypress="return 
    clickButton(event,'Button1')"  />
+12
source

. DefaultButton, . DefaultButton = "IdOfTheDefaultButtonForControlsInThisPanel"

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx

+4

Using jQuery , this is pretty easy to accomplish:

$(function ()
{
    $("#id-of-textbox-1, #id-of-textbox2, etc.").keyup(function (e)
    {
        if (e.keyCode === 13) $("#id-of-submit-button-1").click();
    });

    // And for the second group

    $("#id-of-textbox-3, #id-of-textbox4, etc.").keyup(function (e)
    {
        if (e.keyCode === 13) $("#id-of-submit-button-2").click();
    });
});

If you use ASP.NET Button controls, be sure to set the false property to false UseSubmitBehavior.

+1
source

All Articles