user1773603
user1773603

Reputation:

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
}

Upvotes: 2

Views: 924

Answers (2)

ullfindsmit
ullfindsmit

Reputation: 300

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>

Upvotes: 0

p-a-o-l-o
p-a-o-l-o

Reputation: 10047

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.

Upvotes: 2

Related Questions