How to display confirmation message when a user clicks a checkbox - javascript

I'm having issue trying to display a confirmation message when a checkbox is clicked. The confirmation box appears but doesn't perform any type of action such as displaying the text within the textbox when the user confirms OK. Any advice would do. Thanks in advance!
Here is the code.
<div>
<asp:CheckBox ID="CheckBox1" runat="server"
OnCheckedChanged="CheckBox1_CheckedChanged"
OnClick="if(!confirm('Are you sure you?'))return false;" />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "blah";
}

Well, a check box is not like a button. There is no OnClientClick for a check box.
However, you CAN use OnClick.
Also, the code stub (code behind) you have does NOT run like a button click UNLESS you set AutoPostback = true.
However, you can do it this way:
<asp:CheckBox ID="CheckBox1" runat="server"
OnClick="if (!confirm('really do this')) {return false;}"
AutoPostBack="True"/>
You have to use the !not, and exit from the JavaScript routine, or you MUST LET the JS code continue, since it will do a post back for you. So, the above code spit out by asp.net becomes this:
<input id="CheckBox1" type="checkbox" name="CheckBox1"
checked="checked"
onclick="if (!confirm('really do this')) {return false;};
setTimeout('__doPostBack(\'CheckBox1\',\'\')', 0)">
So, we HAVE to let the js code "continue if we want ok, but if we don't confirm, then we MUST do a return false and exit the js code stub else the post back will in fact run regardless of returning true or false. If fact even if we return true, then the stub exits and the following postback code never will run. So a return with either value still bails out of the generated code stub.
So the check box does NOT support the standard for most buttons in that you use js to return true, or false and thus as a result the post back does not occur.
We can't use say return confirm('Please hit ok') like we can for a button, since if we "return" a value then the post-back code that follows never runs.
So, for a button, the OnClientClick() return value (true/false) is tested for you, and that determines if the button post back will fire. Not so with a check box, and no OnClientClick is defined or supported. But as you can see above we can trick the page processor into working - since it simply appends it own post back code to what we stuff into OnClick.
But, a check box is different, and it does not really support OnClientClick. But if you shove code into OnClick(), then you can see the final rendered output. We thus LET the continue contine to run the postback if we confirm, but bail out (return false) if you don't confirm and the post back code that follows simply does not run.

Related

How can prevent postback page in the case of using both a JavaScript and a C# method on a button?

This is an ASP.NET C# question.
<script>
function buttonfunc() {
document.getElementById("demo").innerHTML = "js work";
}
</script>
<form id="form1" runat="server">
<div>
<p id="demo"></p>
<asp:Button ID="UpdateButton" runat="server" Text="Update"
OnClick="UpdateButton_Click" OnClientClick="buttonfunc()"; return false;/>
</div>
</form>
protected void UpdateButton_Click(object sender, EventArgs e)
{
Response.Write("cs work");
}
In the case of using both a JavaScript and a C# method on a button, how can we stop postback page and display two lines of text at the same time (if possible, without using AJAX)?
The way this works is rather handy.
While that button can have both a client side event, and a server side event?
If the client side js code/event returns false, then the server side event will not trigger. This is ideal for say prompting a user to delete a record, or to perform some operation that you require a "confirm" for.
so, take this button:
<asp:Button ID="cmdDel" runat="server" Text="Delete record"
CssClass="btn"
OnClick="cmdDel_Click"
OnClientClick="return DelConfirm()" />
<script>
function DelConfirm() {
return confirm("Really delete this reocrd?")
}
</script>
so, if the js code (client side) returns true, then server button click runs. If client side js code returns false, then server side button does not run.
You would see this for running above:
and display two lines of text at the same time
Hum, that is not clear what you goal here. What 2 lines are you looking to display here?
I mean, either you want/have the server side button event code run, or it does not. As noted, if you return false, then you should not be seeing a post-back. With your sample code, the return false should result in the server side button even NEVER running.
I mean, if you don't do a post-back, then it does not make sense that you can/will have the server side button code run. You require a post-back for this to occur.
Now, you might be able to live with a update panel, and that allows you to define ONLY that part of the web page that will travel up to the server, and run your code. From a user point of view, the page will not appear to have a post back (and you don't actually have a full page post back in this case). The brower scoll bar will not change postion, and you not see the browser "spinner" show a post-back.
So, you drag + drop in the script manager, and then inside of the update paneel, you would have this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete record"
CssClass="btn"
OnClick="cmdDel_Click"
OnClientClick="return DelConfirm()" />
<script>
function DelConfirm() {
return confirm("Really delete this reocrd?")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Now, in your code exmaple, place everything inside of the content template, and remove your return false for the client side click. give it a try.
Now, some caution with above. The page life cycle DOES trigger. So, the page load event will fire (like it always does), and then your code stub will run. but to the user, you not see a full page post back. This is often called a "partial page" post-back.
Needless to say, to build a working web forms page, 99% of the time, your page load event that sets up values for controls and does things on the FIRST page load ONLY?
You have the !IsPost back stub in the page load event, so your REAL first time page load code only ever runs one time.
eg:
if (!IsPostBack)
{
// first time page load
// load up grid, some combo boxes etc.
// this code only runs ONE time, on first page load
}

__doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page

I have identified a problem with __doPostBack and found a work around. I am seeking an explanation for the cause and/or a better solution than my work around.
Scenario:
I have a dropdown populated with the values; "-Select-", "One" & "Two". If the user selects "One" than client side script is executed. If the user selects "Two" than server side script is executed.
Problem:
The client script initiates the postback by calling __doPostBack. However, no post back actually occurs unless there is also a LinkButton, Calendar or WizardStep control on the page. I actually went through all of the standard tools in the Visual Studio Toolbox and tested them all. It has to be one of those three.
Work Around:
Add a link button surrounded by a span with display set to none.
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Question: Can somebody provide an explanation for this behavior or provide a better fix than my "Work Around"?
Source - Javascript (I placed it between the head tags)
<script language="javascript" type="text/javascript">
function DropDownList1_change(elementRef) {
var selectedIndex = elementRef.selectedIndex;
if (selectedIndex > 0) {
var selectedValue = elementRef.options[selectedIndex].value;
if (selectedValue == "One") {
alert("Because you selected 'One', special javascript code will be executed");
// Special javascript code goes here
return;
}
else if (selectedValue == "Two") {
// Special server code gets executed on server DropDownList1_SelectedIndexChanged
__doPostBack('DropDownList1', '');
}
}
}
</script>
Source - ASPX Controls
<asp:DropDownList ID="DropDownList1" runat="server" onchange="DropDownList1_change(this)" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>-Select-</asp:ListItem>
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:DropDownList>
<br />
<!-- For some unknown reason __doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page -->
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Time of last Post Back: <asp:Label ID="Label1" runat="server"></asp:Label><br />
Time of OnSelectedIndexChanged: <asp:Label ID="Label2" runat="server"></asp:Label>
Source - Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Additional Resource - I found the following article after posting this question. Its a very old Microsoft article and the only Microsoft article I found that mentions the specific limitation of DropDowns, return values & postbacks. I haven't digged deep into their solution and not sure time will allow me to. Mainly posting it in case my solution fails down the road or doesn't work for someone else.
Intuitively you might think adding a confirm dialog box for a
DropDownList is identical to adding such a dialog box for a Button Web
control. That is, simply set the DropDownList's client-side onchange
attribute to something like: return confirm(...);. using:
DropDownListID.Attributes("onchange") = "return confirm(...);"
Unfortunately, this won't work as desired because an AutoPostBack
DropDownList's onchange attribute will be set to a bit of JavaScript
that causes a postback, namely a call to the client-side __doPostBack
function. When setting the onchange attribute programmatically
yourself, the end result is that the rendered client-side onchange
event handler has both your code and the call to __doPostBack:
The article is long so search for "Confirmation with AutoPostBack DropDownLists"
https://msdn.microsoft.com/en-us/library/aa479302.aspx
There are 2 solutions.
Solution 1:
A better work around than adding a link button surrounded by hidden span tags is to add the following to the page load event. This ensures that the function __doPostBack is available.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.GetPostBackEventReference(this, string.Empty);
}
The function __doPostBack is generated only if a control in the form needs it to perform postbacks. This includes controls like the LinkButton and other controls for which AutoPostBack is set to true. In fact, only the Button and ImageButton controls can perform postbacks without __doPostBack (see this article). For example, we can see in the HTML output that a LinkButton is rendered this way:
<a id="lnk" href="javascript:__doPostBack('lnk','')">My link</a>
Solution 2: The following approach achieves the same thing without using __doPostBack.
In the present case, you could set AutoPostBack="true" for the DropDownList:
<asp:DropDownList AutoPostBack="true" onchange="if (!confirmPostBack(this)) return false;" ... >
The onchange event handler would return false when you want to prevent the postback. The Javascript function could be something like this:
function confirmPostBack(ddl)
{
if (condition) {
...
return true;
}
else {
...
return false;
}
}
Important: The onchange event handler should not return anything to allow the postback to occur. You can use this syntax:
onchange="if (!confirmPostBack(this)) return false;"
For reasons probably explained in the article mentioned in the question, the following syntax does not work. Returning true still prevents the postback.
onchange="return confirmPostBack(this);" // Does not work!

User confirmation from server side

I want to confirm user to proceed the saving .
Let's say I have two processes , Process-One and Process-Two .
After complete Process-One , I want to show confirmation message box to user to proceed saving Process-Two .
protected void btnSaveProcess_Click(object sender, EventArgs e)
{
..Saving Process-One....
..Saving Process-One Complete....
// here to show "Are you sure you want to Save Process-Two"
//if user confirm "OK" , save Process-Two
//if user "Cancel" , stop and cancel saving Process-Two
}
Actually , I'm a little weak in Javascript . How can I make this process using Javascript ?
TIA :)
Since you said you are not great with javascript, you can try this. Break the process into 2 buttons, first part is done in btnSaveProcess_Click, and now make a second button btnSecond. btnSecond will handle the second part, after btnSaveProcess_Click is done have it trigger the click event of the btnSecond button. when you create the btnSecond set it up with an alert like:
<asp:Button id="btnSecond" Text="2nd Button" CssClass="HideMe" runat="server" OnClientClick="javascript:return confirm('Would you like to proceed?');"/>
this way the 1st button completes and calls the 2nd ones click. that will cause the alert to come up, if the user clicks ok it proceeds to the 2nd ones event, if the user hits no it doesn't continue.
you could use the ASP.NET AJAX Control Toolkit. it has a ConfirmButtonExtender that will show a confirm dialog before triggering the asp.net postback.
if you want some thing more lightweight you could add the following to a asp.net button onClientClick="return confirm('Are you sure?');"

OnClick not working when i use both Onclick & OnClientClick

With this code, i try to Close a Window (the way i'm doing it works) but i have also an Onclick event which is ignored!
<script type="text/javascript">
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseDialog() {
GetRadWindow().close();
}
ASPX page:
<asp:Button ID="Button1" runat="server" Text="Soumettre ce ticket"
onclick="Button1_Click" OnClientClick="CloseDialog();return false;"/>
My application never enters Button1_click event, can anyone help me to find out why ?
thanks in advance
EDIT: HTML GENERATED FOR THE BUTTON
<input type="submit" id="Button1" onclick="CloseDialog();" value="Soumettre ce ticket" name="Button1"/>
This article kind of explains the problem. You need to return true in your JS if you want the server event to trigger. Otherwise, you have to return false.
And, it also looks like you will have to add the UseSubmitBehavior = false based on: OnclientClick and OnClick is not working at the same time?
This is especially evident after seeing that your generated HTML only has the CloseDialog() and not the call to Button1_Click. This change will concatenate to the end of your onclick.
<asp:Button ID="Button1" runat="server" Text="Soumettre ce ticket"
onclick="Button1_Click" OnClientClick="CloseDialog();"
UseSubmitBehavior="false"/>
I ran into this problem and using UseSubmitBehavior="false" nearly did the trick. Be sure to have your OnClientClick call set up correctly:
My code was using OnClientClick="return ValidateSearch();" which is incorrect. It should just be
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click" OnClientClick="if (!ValidateSearch()) { return false;};" />
See the Source here (and tell them thanks!)
If it is set up incorrectly, the OnClick function will not fire.
You are returning false in the onclientclick, so the event is returned before the postback. As a result, onclick never fires.
I just came across the same issue, and I think we're getting confused between server side enable="false" and client-side "disable".
The serverside property to enable a control using control.Enabled = "false"; is not the same as applying an Attribute, like control.Attribute.Add("disabled","disabled");
If you apply the Enabled = false; from the server side, you're actually turning off the control entirely, even if it's shown on the screen! Go on, try and right click the control and select Inspector or FireFly to see it. Nothing shows up. Nothing happens, because the control does not "exist".
Yet if you apply the Attribute property the control is visible to the server and the client, and you're able to inspect it.
What I did is set up the default environment on the ASP.net side by saying the control (asp:Button in my case), has Enabled="true" (or not saying anything, as that's the default anyway).
On the server side, upon PageLoad(), I make my button Visible (in my case I also had it defaulted to visible="false"), and add the appropriate Attribute values.
btnSEND.Visible = true;
btnSEND.Attributes.Add("disabled", "disabled");
That way the button is not enabled, but it's not entirely "invisible" to the client, and by using JavaScript in another area of my program, I control when to enable it or not.
This method also avoids having to use the UseSubmitBehavior="false".
in page_load, you pass the java script function using Add.Atribute method with return true. first it will load the javascript function. then it will load the button click event

Conditional confirm prompt in asp.net code behind

I have looked around for a way of implementing this. Here is a pseudocode representation of what I have:
bool hasData = ItemHasData(itemid);
Confirm = "false"; // hidden variable
if (hasData)
{
//Code to call confirm(message) returns "true" or "false"
if (Confirm == "true")
{
//Delete item
}
else if (Confirm == "false")
{
return;
}
}
The code to call confirm uses a asp:Literal control and sets it equal to the confirm. I can get the popup but only after the function exits. And it does nothing with the conditions after that.
The general consensus seems to be that calling the javascript at that specific line is impossible (makes sense due to the server side/client side gap), but how can I achieve this? I tried using the ConfirmButtonExtender from the ASP.NET AJAX Toolkit but I couldn't interact with the confirmbuttonextender object from the code behind when the object is set to runat="server".
edit:
Sorry, I did miss those tidbits. Thanks Icarus.
The control itself is the GridView (the pseudo version is actually from the gvData_RowCommand function)'s rowcommand. The first check looks to see if the CommandName is DeleteItem and if so goes into this.
The gvData's columns are set based off a list of headers (and the dataset) passed as the table it is working against is for multiple items with different required information. The gvData's data is there, I just need to get a Yes/No (or in reality it'll end up being Ok/Cancel) dialog to verify they want to delete the item when there is data.
One method I end up using in some situations is to have a Panel that displays the Confirm / Cancel buttons. This avoids the need to handle JavaScript events and uses ASP.NET entirely.
<asp:Panel ID="pDeleteConfirm" runat="server"
CssClass="AlertDialog"
Visible="False">
<p>Do you wish to delete the selected record?<br />
<asp:Button ID="btDeleteYes" runat="server" OnClick="btDelete_Click" Text="Delete" />
<asp:Button ID="btDeleteNo" runat="server" OnClick="btDelete_Click" Text="Cancel" />
</p>
</asp:Panel>
<asp:GridView ID="gvData" runat="server"
AutoGenerateColumns="False"
CssClass="GridView"
DataKeyNames="ID"
DataSourceID="sqlData"
EmptyDataText="There is no data entered in the system."
OnRowDeleting="gvData_RowDeleting">
......
</asp:GridView>
I use the OnRowDeleting event to show the Panel
protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Show confirmation dialog
pDeleteConfirm.Visible = true;
// Select the row to delete
gvData.SelectedIndex = e.RowIndex;
// Cancel the delete so the user can use the confirm box
e.Cancel = true;
}
Handle the button Click events
protected void btDelete_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
switch (bt.ID)
{
case "btDeleteYes": // they confirmed a delete
sqlData.Delete();
break;
case "btDeleteNo": // they clicked cancel
// Do nothing
break;
default:
throw new Exception("Unknow button click in btDelete_Click");
}
// clear selection and hide the confirm box
gvData.SelectedIndex = -1;
pDeleteConfirm.Visible = false;
}
This isn't JavaScript but you can add in some UpdatePanels to do AJAX work on it.
Just one method to do it through ASP.NET rather than JavaScript handling.
The job of your code-behind is to render HTML out to the browser. It does this, and then the socket is closed and your server side code is no longer executing.
You'll have to implement this logic using a Javascript function on the client side.
Are you attempting to warn the user if there's data loaded before they take a certain action? Or perhaps before they try to leave the page? You'll have to popup the alert using script when that action happens on the page.

Categories

Resources