Reputation:
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
Upvotes: 2
Views: 11976
Reputation: 1
<asp:CheckBox ID="chkbox" runat="server" AutoPostBack="false"
onclick="javascript: SomeFunction();" />
This will help. I struggled a lot on this one and found the solution. Make sure that the "onclick" text is all small letters.
Upvotes: -1
Reputation: 11
JavaScript Confirm on check-box, See the following it is very simple and working:
<asp:CheckBox ID = "cbx_CoBorrNotPresent" runat="server" Text="Not Present"
AutoPostBack="false" TextAlign="Left" Checked="true" onclick="javascript:ChkClick();" />
<script id="igClientScript" type="text/javascript">
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;
}
};
</script>
Upvotes: 1
Reputation: 827436
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
}
};
};
Upvotes: 0
Reputation: 187050
CheckBox1.Attributes["onclick"] = "Check();";
function Check ( elem )
{
if ( window.confirm ( "are you sure you want to do this?" ) )
{
__doPostBack ( '' , '' );
}
else
{
return false;
}
}
Upvotes: 2