简体   繁体   中英

OnClientClick event not firing

In the webpage I'm building, I have a div that I need to have hidden by default, and for it to appear when the user clicks on a link button. This is the code for the link button and the following div:

    <asp:LinkButton runat="server" Text="Words & stuff go here"
        OnClientClick="button_Click"></asp:LinkButton>

    <div id="Calculator" runat="server" visible="false">
        //CODE GOES IN HERE 
    </div>

And here is the code in the cs file for the link button:

void button_Click(object sender, EventArgs e)
    {
        if (Calculator.Visible)
            Calculator.Visible = false;

        else if (!Calculator.Visible)
            Calculator.Visible = true;
    }

I have a breakpoint inside the code behind, and when I debug, the breakpoint is never reached, and I have no idea why.

on client click is for client side events. You have to use onClick="button_Click" to make it work.

OnClientClick expects that the button_Click event is defined in javascript on the page, not in C# in the code-behind.

See this .

The OnClientClick property of an ASP .NET control references a client-side function, which means that it will attempt to call a JavaScript function.

You have two options to fix your code.

Option 1:
If you want the button to do a Postback and call your button_Click function in your .cs file, you could just change your button code to:

<asp:LinkButton runat="server" Text="Words & stuff go here" OnClick="button_Click"></asp:LinkButton>

Option 2:
If you wish to use OnClientClick , you could do something similar to the following (in your .aspx file):

<script type="text/javascript">
function button_Click() {
  var calculator_id = '<%= Calculator.ClientID %>';
  var calculator = document.getElementById(calculator_id);
  if (calculator.style.display == 'none') {
    calculator.style.display = 'block';
  } else {
    calculator.style.display = 'none';
  }
}
</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