Triggering a postback event with an alert upon confirmation in an ASP.NET button

Encountering an issue with the javascript alert in my ASP.NET application. I have a button that deletes a user from the database. However, users may have associated documents and insurance policies.
I want to trigger a javascript alert if the user has any documents or policies. The alert will prompt: "You need to delete documents and/or policies." If the user does not have any of them, a confirmation box should appear giving you the option to proceed with the deletion.
Here is a snippet of my .aspx code:

<asp:Button ID="btnDelete" class="btn btn-danger" runat="server" Text="Delete" OnClick="btnDelete_Click" 
                                                                onClientClick="check()">
                                                            </asp:Button>

The function check() looks like this:

function check() {
            var totalRows = $("#<%=gvDocuments.ClientID %> tr").length-1;
            var totalRows1 = $("#<%=gvPolice.ClientID %> tr").length-1;
            if (totalRows > 0 || totalRows1 > 0) {
                alert('Delete ' + totalRows + ' documents and ' + totalRows1 + ' policies of the client before proceeding with the deletion!');
//Checking if there are any documents or policies
                return false;
            }
            else {
                var r = confirm('Are you sure you want to delete the client?');
                if (r == true) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }

The confirm block functions correctly. Pressing OK proceeds with the deletion, while Cancel returns false.
My concern is when the user clicks OK on the alert, it triggers a postback and deletes the user without deleting the documents and policies. Is this returning true? Thank you, Regards

Answer №1

When examining your button in the browser, you'll notice that Asp.net will automatically trigger its doPostback javascript either immediately after your onclientclick code runs or upon form submission.

Therefore, even if your function call returns true/false, the doPostback will still be executed regardless.

To prevent this behavior, you should manage the return of your function inline as shown below:

onClientClick="if(check() === false){return false;}"

By explicitly returning false in this case, you can halt the execution of the javascript and prevent the postback from occurring :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some quality open APIs available for web-based frontend painting tools?

I am in the process of creating an HTML5/JavaScript application inspired by: Although I could simply copy and paste their source code, I am concerned about potential copyright issues. Instead, I am exploring the option of using free APIs that offer simila ...

A shortcut for calling functions in Lodash

Looking to execute a series of functions using Lodash? Here's an example: const functions = [ () => console.log('Fn 1'), () => console.log('Fn 2') ]; _(functions).each(fn => fn()); Wondering if there is a Lodash ...

Is it possible to replicate the functionality of RadTreeList in Gridview/Jquery?

There is a control called RadTreeList by Telerik that we do not use in our current project, but wish we did. If you want to see an example of it, you can visit this link: Currently, I need to find a way to represent the number of applications associated ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Arranging routes in node.js like a pro

const express = require('express'); const router = express.Router(); router.use(function(req, res, next){ console.log(req.user) if(!req.user){ res.redirect('/login'); }else{ res.locals.username = req.user.us ...

Programmatically Generated Checkbox Inside GridView Row Triggers Checked_Change Event

I am working with a GridView that displays user data. On the Page_Load method, I retrieve data using a DataTable and bind it to the GridView. Each row in the GridView contains a CheckBox, serving as a reference for editing a specific entity. The challenge ...

Is there a method to retrieve the bounds (northeast and southwest) of the map display when there is a change in the bounds, center, or view area?

In my NextJs project, I am utilizing the TomTom Map SDK to implement a feature where, upon loading the map based on its bounds, I query for nearby restaurants in that specific area. Additionally, when there are zoom or drag events on the map, I want to mak ...

Instructions for receiving user input and displaying it on the screen, as well as allowing others with access to the URL to view the shared input provided by the original user

<h1>Lalan</h1> <input type="text" name="text" id="text" maxlength="12"> <label for="text"> Please enter your name here</label> <br><input type="submit" value ...

Utilizing AJAX to automatically fill out a form with information retrieved from a MySQL database

I have been attempting to automate the population of a form with data when a gymnast is selected from a dropdown box. I am aware that AJAX needs to be used for this purpose, and despite my best efforts, my lack of proficiency in Javascript has resulted in ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

What is the best way to upload a file using AJAX request in Sinatra?

I am attempting to upload a file using a jQuery AJAX function with a Ruby-Sinatra function. Here is the code snippet: <form id="ucform" method="post" action="#" enctype="multipart/form-data"> <input type="file" id="cfile" name="cfile" onchange= ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...

The getBBox() method of SVG:g is returning an incorrect width value

Hey there, I've been attempting to determine the width of a <g> element and it consistently returns 509.5 pixels regardless of what I do. Initially, I assumed this was the actual size and not scaled. However, upon opening the SVG in Illustrato ...

A useful tip for emphasizing tags that have attributes with endings

Here is the HTML list I'm working with: <li class=​"info" data-info=​"" data-title=​"info 1" data-info-id=​"222643">…</li> <li class=​"info" data-info=​"" data-title=​"info 2" data-info-id=​"217145">…</li> ...

jQuery Scrolling Page Issue Not Resolved

I am diving into the world of JavaScript and attempting to develop a simple program that smoothly scrolls to a specific div when a navigation item is clicked. Unfortunately, my code is not functioning as expected and I am struggling to identify the root ca ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

Using the readline function in JavaScript, a sequence of user inputs can be collected. These inputs can be linked to

Within my array var questions=[], I have stored multiple questions. Currently, I am using forEach to iterate through the array and prompt the user for input on each question, displaying the responses in the terminal. However, I am facing an issue where onl ...

When running 'npm run dev', an error occurred after the SizeLimitsPlugin emitted at 98%. The specific dependency that was

I encountered an issue while trying to incorporate Google Maps into my Laravel project and received the following error message after running npm run dev: 98% after emitting SizeLimitsPlugin ERROR Failed to compile with 1 errors 10:52:34 PM This dependen ...

How come my web page is not displaying the guages from guage.js?

I am utilizing guage.js to create a graph based on this Fiddle. However, upon adding the same code to my website, the rendering does not appear as expected: https://i.sstatic.net/fIkQr.png Upon inspecting in Chrome developer tools, I noticed that the ele ...

Shifting a portion of Controller logic to a Service in AngularJS

Here is some code you should consider: HTML: <!doctype html> <html ng-app="todoApp"> <head> ... </head> <body ng-controller="MainController as myControl"> ... </body> </html> Angu ...