6
    protected void btnNext_Click(object sender, EventArgs e)
    {
        btnNext.InnerHtml = "CLICK";
    }

    <button type="submit" runat="server" onserverclick="btnNext_Click" id="btnNext">Next &gt;</button>

This works fine, but when I add an onclick event:

<button type="submit" runat="server" onserverclick="btnNext_Click" onclick="return checkForm();" id="btnNext">Next &gt;</button>

And in the head:

<script type="text/javascript">

    function checkForm() {

        if (document.getElementById("<%=lstChooseSpec.ClientID %>").value) {
            return true;
        } else {
            $.jGrowl("<strong>Warning!</strong><br />Please select an item", { sticky: true });
            return false;
        }
    }
</script>

It submits the form, but doesn't change the buttons text to 'CLICK'. The text only changes to 'CLICK' when the onclick() isn't defined, although the form is still submitting!

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • 8
    Is there a reason you can't use an instead of a – Becuzz Jan 28 '11 at 15:49
  • Note the difference of an HTML – Don Cheadle Nov 07 '19 at 21:47

5 Answers5

9

try without 'return': <button type="submit" runat="server" onserverclick="btnNext_Click" onclick="checkForm();" id="btnNext">Next &gt;</button>
Or if you wanted checkForm() to control whether to post or not - do like this:

onclick="if (!checkForm()) return;"
Roman Asanov
  • 287
  • 2
  • 6
8

The reason you're seeing this is because when you have both on a button it runs your on click handler followed by the __doPostBack function so the onclick would look something like this

onclick="return checkForm(); __doPostBack('btnNext','')

So as you can see the __doPostBack, which actually sets up which server function to call, is never called. However, since the button is of type submit, the form is still sent back to the server.

Vadim
  • 17,897
  • 4
  • 38
  • 62
  • 1
    Note the difference of an HTML – Don Cheadle Nov 07 '19 at 21:50
0

Try this:

onclick="javascript:if (!validaForm()) return false;"

It worked for me.

josliber
  • 43,891
  • 12
  • 98
  • 133
Ricardo Gaefke
  • 823
  • 1
  • 7
  • 21
0

Front End

  <button  id="submit1" runat="server"  
              onclick="if(confirm('Sure?')) { } else{ return false} ;"                       onserverclick="submit_ServerClick"  >save</button>

Back End

 protected void submit_ServerClick(object sender, EventArgs e)
 {
 }
Liam
  • 27,717
  • 28
  • 128
  • 190
Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
0

Can you try with LinkButton:

<asp:LinkButton type="submit" runat="server" onserverclick="btnNext_Click" onclick="return checkForm();" id="btnNext">Next &gt;</asp:LinkButton>
Gauravsa
  • 6,330
  • 2
  • 21
  • 30