I have a textBox and I want to create a confirm message on text_changed event and execute different codes on ok and cancel in code behind under text_changed event
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
window.confirm returns a boolean, in your button you could add onclick="trigger_confirmation"
var trigger_confirmation = function(){
if(window.confirm("Are you sure blah blah blah?")){
// user confirmed
} else {
// user declined
}
}
To achieve your functionality you have to do following
Make AutoPostBack="True" of your text box.
Add one hidden filed and add java script like following code example in aspx page.
Note: java script block must be come after you hidden field and text box control.
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
ontextchanged="TextBox1_TextChanged" ></asp:TextBox>
<script type="text/javascript">
var textChange = document.getElementById('<%= TextBox1.ClientID %>').getAttribute("onchange");
document.getElementById('<%= TextBox1.ClientID %>').setAttribute("onchange", "JustConfirm();");
function JustConfirm() {
var IsConfirm = confirm('Confirm event?');
var hdnctrl = document.getElementById('<%= HiddenField1.ClientID %>');
hdnctrl.value = IsConfirm ? 'yes' : 'no';
eval(textChange);
}
</script>
Now in server side put code check as following
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (HiddenField1.Value == "yes")
{
// Any c# code for confirmation
}
else
{
// Any c# code for not confirmation
}
}
try this code inside your TextBox1_TextChanged
block:
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script>if(window.confirm('Press ok to continue?')){// on ok clicked }</script>");