9
votes

I have a LinkButton where I use the OnClientClick property to ask the user whether he really wants to perform an action, e.g:

<script>
function confirmDelete() {
  return confirm('Do you really want to delete?');
}
</script>

<asp:LinkButton runat="server" OnClientClick="return confirmDelete()" ... />

This pattern usually works, but on this specific page, it doesn't. No matter whether I click OK or Cancel in the confirm dialog, the postback is executed.


Just for completeness (to answer pst's question): the rendered HTML is OK. E.g. it looks like this:

<a id="ctl00_c1_content_btnDelete" onclick="return confirmDelete();"
 href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(..))"
... >
  Delete
</a>
3
The resulting HTML generated is...?user166390
@pst: the HTML is OK. See my answer below - I just posted this for others which might have the same problem.M4N
@pst: can't yet - have to wait until tomorrow ;-)M4N

3 Answers

8
votes

The reason for the behavior was another piece of javascript, where a handler for the link(button)'s click event was registered via jquery, e.g. something similar to this:

<script>
$(document).ready(function() {
  $('a').click(function() {
    // ...
    return (someCondition == true);
  });
});
</script>

It seems this click-handler was called after the one registered by OnClientClick, and when this one returned true, then the postback occurred, independent of the result of the first click-handler (the confirm dialog).

1
votes

Here is something which worked for me.

<asp:LinkButton runat="server" OnClientClick="return (!confirmDelete()){return false;}" />

Javascript

    function confirmDelete(){
    if(something == true){
    return true;
    }
    else{
    return false;
    }
    }
0
votes

very good! The OnClientClick="return Confirm('')" is worked for me.