Reputation: 2379
This is my javascript method in .aspx file. I want to invoke this method from code-behind based on a certain condition:
function confirmboxAndHideMessage() {
//HideMessage();
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
}
else {
HideMessage();
return true;
}
}
The condition upon which I want to invoke is something like this:
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.Attributes.Add("OnClick", "javascript:return confirmboxAndHideMessage();");
}
else
{
btnProceedAddNewRecords.Attributes.Remove("OnClick");
}
This condition is being exercised in a method which is called in PageLoad event inside
if (!IsPostBack) { /* condition */ }
It is not working and my guess is that the way i am adding the method in button attribute is wrong. My request is that, kindly suggest a way I can invoke this javascript method from my code-behind based on the stated condition. If you think that my approach is flawed, Please do suggest Alternatives. Thanks.
Upvotes: 1
Views: 2244
Reputation: 700432
You should return true
or false
from the function. You probably want to return true for a positive response:
function confirmboxAndHideMessage() {
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
return true;
} else {
HideMessage();
return false;
}
}
Use lowercase for the event name (as XHTML is picky about that), and remove javascript:
from the code:
btnProceedAddNewRecords.Attributes.Add("onclick", "return confirmboxAndHideMessage();");
Put the code that sets the attribute outside the check for IsPostBack
, otherwise it will not be updated when the condition changes.
Upvotes: 1
Reputation: 35572
use to set/unset OnClientClick
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.OnClientClick="return confirmboxAndHideMessage();";
}
else
{
btnProceedAddNewRecords.OnClientClick="retun false;";
}
Upvotes: 1
Reputation: 6918
Just add the following code where the condition is like
public void test()
{
String name = "test";
if (name == "test")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "hdrEmpty", "if(confirm('are you sure you want to continue?')==true){ Testfunction(); };", true); return;
}
}
I am sure it will work for you.
Upvotes: 1