How to display confirmation message when a checkbox is clicked - c#

I want to be able to display a confirmation message when asp.net checkbox is clicked, i tried using:
OnClientClick = "return confirm('Are you sure you want to logout?')"
It doesnt report error, but not working, i later found out that asp.net checkbox doen't have OnClientClick attribute.
I have also done a few research on google still couldn't achieve! Please does anyone know how to do this? Thanks in advance.

After much research i was able to implement this, here is the answer so other users who are facing this same issue can use it:
OnClick="if(!confirm('Are you sure you want to sign out?'))return false;" this works perfectly for me.

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});

You can have a look at here
Checkbox check confirmation message.
You can do that by using javascript, by checking the count of the checkbox.
Like below
if (chkCount === 0) {
alert("You do not have any selected files to delete.");
return false;
} else {
return confirm("Are you sure you want to proceed deleting the selected files?");
}
Hope that helps

Since you did not mentioned below is jquery
$(document).ready(function() {
$('#yourelemntid_as_enderedHtml').change(function() {
if ($(this).prop('checked')) {
alert("Are you sure you want to logout."); //checked
}
else {
alert("text here"); //not checked
}
});
});
you also better call it on EndprocessRequest() as well as asp loose this script
And in c#
<asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>'
OnCheckedChanged="chkgen_OnCheckedChanged"/>
protected void chkgen_OnCheckedChanged(object sender, EventArgs e)
{
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
CheckBox cb = (CheckBox)gridView.Rows[selRowIndex].FindControl("chkgen");
if (cb.Checked)
{
//Perform your logic
}
}

You can use onchange in asp:checkbox, like this -
<asp:CheckBox Text="check this out" runat="server" onchange="return confirm('Are you sure you want to logout?');" />
If you have set autopostback = true, it will postback.
Problem with this is it will work for every change - be it check or uncheck, to mitigate this you can use it like this.
<asp:CheckBox Text="check this out" runat="server" onchange="return Confirmation(this);" />
function Confirmation(element)
{
if(element.checked) // so that only for checked case, this will execute.
return confirm('Are you sure you want to logout?');
else
return false;
}

Related

How to set Textbox's Text as an querystring argument for LinkButton without having codebhind file?

I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>

Delete does not ask for confirmation

When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"

Button onClick doesn't work if it is inside of DIV in ASP.NET

I have a div like as :
<div id="specific">
<table cellpadding="2" border="0">
<tr><td>Choose category</td><td><select id="list_categories" runat="server"></select></td><td><asp:RequiredFieldValidator ControlToValidate="list_categories" runat="server" Display="Static" ErrorMessage="Select category" ID="verify_category"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link name : </td><td><asp:TextBox ID="link_name" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_name" runat="server" Display="Static" ErrorMessage="Provide a name for link" ID="verify_link_name"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link url : </td><td><asp:TextBox ID="link_url" runat="server"></asp:TextBox></td><td><asp:RegularExpressionValidator ID="verify_url" runat="server" ControlToValidate="link_url" Display="Static" ErrorMessage="Invalid link. Must be as http://www.stabiplan.com" ValidationExpression="^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$"></asp:RegularExpressionValidator></td></tr>
<tr><td>Link description</td><td><asp:TextBox ID="link_descr" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_descr" runat="server" ID="verify_descr" Display="Static" ErrorMessage="Provide a link description"></asp:RequiredFieldValidator></td></tr>
<tr><td colspan="2"><center><asp:Button runat="server" ID="add_link_process" Text="Add link" OnClick="add_link_function" /></center></td></tr>
</table>
</div>
and the function from CodeBehind.cs
protected void add_link_function( object sender, EventArgs e ) {
BusinessLayerArcht layer = LoadDataFromBL();
if ( layer.add_link( link_name.Text, link_url.Text, link_descr.Text, list_categories.Value.ToString() ) ) {
messages.Text = "Link added successfully";
LoadTree( tree );
} else {
messages.Text = "Link could not be added !";
}
}
When I click on the button, nothing happens. Why ?
If I remove DIV block and let the code inside the <table>, button click event works.
Thank you
I highly doubt it has anything to do with the div element. Usually, when a button does nothing it's because validation is preventing the postback. To test this, set the CausesValidation property to false on the Button and try again.
Have you tried adding a breakpoint to the add_link_function method to check whether its being triggered at all?
Regarding your validation issue, you can add ValidationGroup to your Validation controls as well as your Button. This way, only validation controls with a matching group name as the triggered button, will be actioned.
may you have to change the property of button " UseSubmitBehavior " to false
This is is a total guess, but it's possible the 'div' is sitting on top of your table and preventing the click getting to the button, you could try some Javascript code like this -
function getActivatedObject(e) {
var obj;
if (!e) {
obj = window.event.srcElement;
} else if (e.srcElement) {
obj = e.srcElement;
} else {
obj = e.target;
}
return obj;
}
function addEventHandler(obj, eventName, handler) {
if (document.attachEvent) {
obj.attachEvent("on" + eventName, handler);
} else if (document.addEventListener) {
obj.addEventListener(eventName, handler, false);
}
}
to work out which element was getting the click event.
Code from - How do I know which element was clicked?
In the properties of that button, set OnClientClick as the name of the function you are calling on "onClick".
It worked for me.

Get the return confirm popbox value in asp .net C#

How can i get the value that was pressed in the confirm box?
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
if (confirm("Are you sure you want to proceed?")==true)
return true;
else
return false;
}
</script>
C#
Button2.Attributes.Add("onclick", "return confirm_proceed();");
Try this, if this is the only button that has this behavior
Button2.Attributes.Add("onclick", "return confirm('Are you sure you want to proceed?')");
it's inline and looks straightforward but if you have multiple controls that behave this way then your original approach would be easy to maintain.
And your original function could be shrunken to
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
return confirm("Are you sure you want to proceed?");
}
</script>
You can store the value of confirm_proceed() in an asp:HiddenField
You can modify your script as follows:
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
var hiddenField = document.getElementById('hiddenFieldId');
if (confirm("Are you sure you want to proceed?")==true)
{
hiddenField.value = 'true';
return true;
}
else
{
hiddenField.value = 'false';
return false;
}
}
</script>
You can now access first the hidden field's value in your Button2_Click event.
I just face similar problem in a real production project and I solved it by the following:
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" onClientClick="return confirm('Are you sure you want to proceed?')"/>
so the OnClientClick Client event is raised befoere the onClick which is a server event , so if the user clicks OK then the Client event returns True from the confirm Dialog and therefore the Code Behind this button is executed , on the other hand if the user clicks (Cancel or No) then it would return false and therefore the code behind wont get exected (Server Event is Cancelled)
hope it would help you as I really applied it to my project and worked without any issues.

Invoking a pop-up 'confirm' message box in ASP.NET

I know how to this when a button is clicked. For example:
imgBtnDelete.Attributes.Add("onclick", "return confirm('Please confirm you want to delete the letter')")
My question is:
Say I have a piece of code-behind not related to clicking,calculating the value of a boolean, and if the boolean is true then I want the message box with ok/cancel to appear.
f.e.:
bool hasMoney = ...
if (hasMoney)
{
\\message box..
}
How do I do it?
You can do something like this:
private void OpenConfirmPrompt()
{
string strScript = "<script language=JavaScript>alert('File Uploaded');</script>";
if (!ClientScript.IsStartupScriptRegistered("open"))
{
ClientScript.RegisterStartupScript(typeof(Page), "open", strScript);
}
}
And change the JS there to suit.
So call that function from a server side event.
Edit, much better explanation than me here
Why not use the Ajax Control Toolkit's ConfirmButton extender? Then rather than writing the JavaScript yourself, you can just set the Enabled property in your code-behind e.g.
<asp:Button runat="server" ID="MyButton" Text="My Button" />
<ajaxtoolkit:ConfirmButtonExtender runat="server" id="MyButtonConfirmExtender" TargetControlID="MyButton" ConfirmText="Continue?" />
and
if (whatever)
{
MyButtonConfirmExtender.Enabled = true;
}

Categories

Resources