views:

1117

answers:

3

In my project in one of the page I am creating a checkbox and doing some server side task when the checkbox check changes. What I want is to show a confirm message before going to the code behind.

If I am calling the javascript function then it is returning true/false(onclick event) but not going inside CheckboxCheckChanged.

I want the confirmation message should appear and depending upon the user input it will go inside the CheckboxCheckChanged event in code behind

+1  A: 
CheckBox1.Attributes["onclick"] = "Check();";

function Check ( elem )
     {
      if ( window.confirm ( "are you sure you want to do this?" ) )
      {
       __doPostBack ( '' , '' );
      }
      else
      {
       return false;
      }
     }
rahul
A: 

I've found this problem a couple of times, when using ASP:CheckBoxes with the AutoPostBack property set to true.

If that property is true, ASP .NET creates an ugly inline onclick event on the generated HTML as this:

<input id="CheckBox1" type="checkbox" name="CheckBox1" 
 onclick="javascript:setTimeout('__doPostBack(\'CheckBox1\',\'\')', 0)" />

So if you set again the onclick event, it will be overriden, and the PostBack won't occur.

I found a workaround to this, is basically to store the original onclick event that ASP .NET generates, and assign a new onclick function, which will show the confirmation, and if the user selects cancel it will return false, otherwise the original click event will be executed normally with the right context and event object, and the postback will occur, for example:

window.onload = function() {
  var checkBox1 = document.getElementById('<%=CheckBox1.ClientID %>'),
      originalOnClick = checkBox1.onclick; // store original click event

  checkBox1.onclick = function(e) {
    if (confirm('Are you sure?')) {
      originalOnClick.call(this, e); // call the original click with the right
                                     // context and event object
    } else {
      return false;  // cancel the click
    }
  };
};
CMS
A: 

JavaScript Confirm on check-box, See the following it is very simple and working:

function ChkClick() { var checkBox1 = document.getElementById('ctl00_cph_PageContent_cbx_CoBorrNotPresent'); if (confirm('Are you sure?')) { __doPostBack('ctl00$cph_PageContent$cbx_CoBorrNotPresent', ''); } else { return false; } };
Nil