简体   繁体   中英

Client side keypress handling event, set focus function, and __doPostBack ASP.NET

I'm trying to do the following :

  • First, a textBox get the focus on page load (no problem here)

  • Then, when ENTER button is pressed inside that textBox, it switch focus to the second textBox.

  • Finally, when ENTER is pressed in that second textBox, it does a postback and reahes code behind event just like when you press a classic <asp:button />

Based on :

Fire event on enter key press for a textbox

and

JavaScript set focus to HTML form element

I managed to come up with :

HTML :

 <asp:TextBox ID="txtNNoSerie" runat="server"  Width="150px" ClientIDMode="Static" onkeypress="EnterEventFirst(event)" AutoPostBack="false"></asp:TextBox>             
 <asp:TextBox ID="txtNNoIdentification" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventSecond(event)" AutoPostBack="false"></asp:TextBox>
 <asp:Button id="btnAjouter" CssClass="ms-Button ms-Button--primary" onclick="btnAjouter_click" Text="+" ForeColor="White" runat="server"  Width="30px" />

    <input type="text" id="txtTest" /> <%-- Just for tests --%>

JS :

  function EnterEventFirst(e) {
      if (e.keyCode == 13) {
          document.getElementById('txtTest').value = 'got it';
          document.getElementById('<%=txtNNoIdentification.ClientID%>').focus();
      }
  } 



  function EnterEventSecond(e) {
      if (e.keyCode == 13) {
          document.getElementById('txtTest').value = 'Again';
          __doPostBack('<%=btnAjouter.ClientID%>', "");
      }
  }

Code behind :

    protected void btnAjouter_click(object sender, EventArgs e)
    {
    }

JavaScript functions are reached, because i can see "got it" and "Again" in the test TextBox, but just for half a second and then it desapear... The __DoPostBack funtion does not work.

Looks like when you press enter in a textBox, it automaticaly does a useless postback and page reload... And that is where i'm stuck

使用ClientID而不是UniqueID。

Well, textBox automaticaly postBack when enter is pressed, ok then.

I did it all on server side, I hate this but i kinda had no choice :

        txtNNoSerie.Focus();
        if (txtNNoSerie.Text != "")
            txtNNoIdentification.Focus();
        if (txtNNoSerie.Text != "" && txtNNoIdentification.Text != "")
            btnAjouter_click(this, new EventArgs());

Server side code... If anyone can show me some working client side code i'll take it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM