Display confirmation box in ASP.NET using JavaScript - asp.net

I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.

function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps

In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>

If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects

if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>

function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.

Related

Prevent double clicking asp.net button

I realise this question has been asked but none of the answers worked for my project.
I have a button that when clicked calls an API, so there is a 1 second delay.
I have tried several things nothing works.
btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Even that does nothing.
Prevent Double Click .Please add below code in your aspx page.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
This solution is simple and effective. On your button include this code:
OnClientClick="return CheckDouble();"
And wherever you want your JavaScript - e.g. At the bottom of your page:
<script type="text/javascript">
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('This sometimes takes a few seconds - please be patient.');
return false;
}
}
</script>
Most of the above suggestions failed to work for me. The one that did work was the following by tezzo:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
Simpler still, rather than using the above in the code-behind, just use the following:
<asp:Button ID="btnSave" runat="server" Text="Save"
UseSubmitBehavior="false"
OnClientClick="this.disabled='true';"
</asp:button>
UseSubmitBehavior="false" is the key.
You can prevent double-clicking using this code:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
So you can use btnSave_Click to call your API.
Usually I have a lot of Validators in my Page: setting Validator.SetFocusOnError = True I can run this code to reenable save button if a validation failed.
Me.YourControl.Attributes.Add("onfocus", Me.btnSave.ClientID & ".removeAttribute('disabled');")
This is the one I found works in all cases.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
</form>
Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
The above script disables the ASP.Net Button as soon as the page is ready to do a PostBack or the ASP.Net form is submitted.
But in cases you might want to disable all Buttons and Submit Buttons on the page hence for such cases I have created another function which disables all Buttons and Submit buttons whenever there’s a PostBack or form submission
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Prevent Double Click .Please add below code in your aspx page
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
At first my solution is like this:
<script>
function disableButton(btn) {
setTimeout(function () { btn.disabled = true; }, 20);
return true;
}
</script>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="return disableButton(this);" />
Without setTimeout the button will be immediately disabled and then the OnClick event will not be fired. The drawback of this approach is that the Save button will not be accessible anymore if some validation fails or some error happens.
So I don't think disable the button is a good solution, and come up with another solution:
function disableButton(btn) {
if (btn.hasclicked) return false;
btn.hasclicked = 1;
btn.onmouseenter = function () { this.hasclicked = 0; };
return true;
}
But my colleague points out that if the post processing is very slow, before it is finished, the user is still able to perform the double postback by leave-enter-click the button. So I figured out another two solutions:
Run the validation from client before submitting the form. But if your page contains multiple ValidationGroup, it is said that the following Page_ClientValidate() should be called multiple times with a passed-in ValidationGroup parameter: e.g. Page_ClientValidate("group1"):
function disableButton(btn) {
if (Page_ClientValidate) {
Page_ClientValidate();
if (!Page_IsValid) {
btn.setAttribute("btnClicked", "n");
return true;
}
}
if (btn.getAttribute("btnClicked") == "y") {
return false;
} else {
btn.setAttribute("btnClicked", "y");
return true;
}
}
As the ASP.NET has only one form in a page (not ASP.NET MVC), we can also let the onsubmit client event of the form to intercept the double click:
function disableButton(btn) {
$("form").submit(function () {
if (btn.getAttribute("btnClicked") == "y")
return false;
else
btn.setAttribute("btnClicked", "y");
return true;
});}
I'll ask QA to test those two approaches(Post edit: QA has proved that it is very dangerous to use this approach. Please refer to my following comments for details).
Try this way, it's a working solution:
For all browsers including Opera Mobile browser which doesn't support js, means your form will not be blocked in that type of browsers.
Add this in Page_load() method:
BtnID.Attributes.Add("onclick", "if(typeof (Page_ClientValidate) === 'function' && !Page_ClientValidate()){return false;} this.disabled = true;this.value = 'Working...';" + ClientScript.GetPostBackEventReference(BtnID, null) + ";");

I want to disable a button when asp RequiredFieldValidator shows error

I want to disable the form submit button when asp:RequiredFieldValidator shows error
please advise
if(Page_ClientValidate("SomeValidationGroup") == false)
document.getElementById("button1").disabled = true;
You could use this javascripot function onchange of the control which triggers validation:
<asp:TextBox id="TextBox1" runat=server OnChange="txtValidate();" />
<asp:RequiredFieldValidator id="validator1" runat="server"
ControlToValidate="TextBox1" ...>
<script>
function txtValidate() {
// trigger validation from clientside
var val = <%= validator1.ClientID %>;
if (val.isvalid == false) {
document.getElementById('btnSubmit').disabled = true;
}
}
</script>
Perhaps you can try something like this:
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
//disable button here
return false;
}
//enable button here
return true;
}
For more information about this function visit and understanding the ASP.NET Validation Library visit this post.
Alternatively, as #Nag suggested, a custom validator may also be able to accomplish this as you are able to define the client side JavaScript.
You should use validationgroup + requirevalidation then the button should not be clickable

ASP OnText event based controlling button control

What I'm trying to do is has a specific button enables or disables based on the number of characters that have been imputed into a textbox.
The event only fire when I click off the textbox, maybe i'm looking for something else?
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnTextChanged="InputVinInformationTextBox_OnText"
AutoPostBack="true">
</telerik:RadTextBox>
protected void InputVinInformationTextBox_OnText(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
If you don't mind using jQuery you could remove the OnTextChanged function and instead bind the functionality to the keyup event. All you need to do is to add the following in your <head> tag:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#<%=InputVinInformationTextBox.ClientID%>").keyup(function() {
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
});
</script>
I'm not sure what your VinSubmitButton is, but I assume, since it was working in your example, that that is an element that you already have stored.
This behavior is by design:
All RadInput controls provide the TextChanged server event, which is
raised when the AutoPostBack property is set to true, the user types
valid entry, and the input loses focus.
The TextChanged event only occurs if the value of the input control
actually changes. If the user changes the string in the input control
but does not actually change the value...the TextChanged event does
not occur.
See this help topic on Telerik's site for more info.
I recommend using the OnTextChanged event as you have been, as it will only fire when valid text is entered that changes the previous value of the RadTextBox.
Alternatively, you can use JavaScript to determine when an appropriate number of characters have been entered, then trigger the request manually.
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnLoad="InputVinInformationTextBox_OnLoad">
<ClientEvents OnKeyPress="InputVinInformationTextBox_OnKeyPress" />
</telerik:RadTextBox>
<script type="text/javascript">
function InputVinInformationTextBox_OnKeyPress(sender, args) {
var text = sender.get_value();
if (text.length >= 8) {
var ajaxManager = $find('<%= RadAjaxManager.GetCurrent(Page) %>');
ajaxManager.ajaxRequestWithTarget(sender.get_id(), '');
}
}
</script>
The code above assumes you are also using a RadAjaxManager on the page and that it has been configured to update all/part of the page when triggered by the RadTextBox. You'd need to check the RadTextBox value during the OnLoad event of the control (or later) so that all ViewState and form values have been initialized for the control.
protected void InputVinInformationTextBox_OnLoad(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}

Display in correct order using RequiredFieldValidators, ValidatorCallout and a ModalPopupExtender of validation is OK

I'm trying to get a sequence of things to happen in the correct order, but no luck. What I have is a number of fields with asp:ReuiredFieldValidators and asp:ValidatorCallout to display validation messages. This is triggered with a button Save with validation="true".
If all validates, it should display a modal dialog asking for two choises on how to save the data. No matter the answer, it should always continue at this stage to code behind save function.The AjaxToolkit_ModalPopupExtender is connected to the same save button.
What happens is that the validation callouts and modal dialog is shown at the same time.
Searched for tips and help but haven't found any, for me, helpful! Most grateful for any help!
Cheers
/Johan
You can show the ModalPopup from codebehind(in BtnSave.Click-handler) if the page is valid:
Page.Validate("YourValidationGroup");
If(Page.IsValid){
ModalPopup1.Show();
}
Therefor you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
You must move to Code Behind only when the Page is validated in client side. You can do it using OnClientClick of button
<asp:Button ID="ShowDialog" onClientClick = "return ValidatePage();"
runat="server" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
return true;
}
else {
// do something else
alert('Page is not valid!');
return false;
}
}
</script>

Avoid postback on button click

I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed
This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()
Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);
If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />
#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}

Resources