简体   繁体   中英

Prevent from a postback and run OnClick using jQuery

I'm trying to validate the TextBox and click the Button of asp.net.

<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" />

And here is a jQuery code which validate TextBox and then trigger the OnClick method:

var al = document.getElementById('<%=lblAlert.ClientID%>');
var email = document.getElementById('<%=txtEmail.ClientID%>');
var msg = null;
$(document).ready(function () {
  $('#<%=btnLogin.ClientID%>').on('click', function (e) {
      if (email.innerText == '') {
          msg = 'Please! enter email address.';
          al.innerText = msg;
      }
      else {
          $('#<%=btnLogin.ClientID%>').click();
      }
  });
});

Edit:

OnClick method is:

protected void btnLogin_Click(object sender, EventArgs e)
{
  // some code
}

You should cancel the click event, when needed, using event.preventDefault() .

$(document).ready(function () {
  $('#<%=btnLogin.ClientID%>').on('click', function (e) {
      if (email.innerText == '') {
          msg = 'Please! enter email address.';
          al.innerText = msg;
          e.preventDefault();
      }
  });
});

No need to call click again if validation succeeds.

Since in the HTML your button is already clicked when the jquery gets called, your

  else {
      $('#<%=btnLogin.ClientID%>').click();
  }

is redundant.

Here is the thing, if you want to validate and then click, then you should use a different element as a button

If you want to use the same button (recommended) then you have to prevent the postback when the validation fails by returning false.

Simple HTML concepts

    <asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="return false;" />

Will never cause a postback

Here is what I would do

<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="ValidateMe()" />
<script>
var al = document.getElementById('<%=lblAlert.ClientID%>');
var msg = null;
function ValidateMe() {
  var email = document.getElementById('<%=txtEmail.ClientID%>');
      if (email.innerText == '') {
          msg = 'Please! enter email address.';
          al.innerText = msg;
          return false;
      }
      else {
          return true;
      }
}
</script>

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