In the realm of asp.net, the OnClick event springs into action after the

My asp button uses OnClientClick to execute a javascript function, and I also want to run OnClick after OnClientClick. However, the OnClick never seems to execute. Despite looking through similar topics on StackOverflow and other websites, I can't seem to get it to work for me.

<asp:Button ID="btn_del" runat="server" Font-Bold="True" Text="DELETE" Width="130px" UseSubmitBehavior="false" OnClientClick="if (!RunDelete()) return false;" OnClick="btn_del_Click" />

function RunDelete() {
        OnDelete("Delete?", function yes() {
            var id = $('#<%=txt_id.ClientID%>').val();

            $.ajax({
                type: "POST",
                url: "/demo.aspx/DeleteRowDb",
                data: JSON.stringify({ "RecordID": id }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                }
            });
            return true;
            
        },
            function no() {
                return false;
            });
    }

I've attempted to create another button with the same OnClick behavior and tried to trigger it from JavaScript using

document.getElementById('<%= btn_del2.ClientID %>').click();
, but it still doesn't seem to work. I really need the OnClick to execute because I rely on the protected void method in the code behind to function correctly, and I'm limited in what I can do within the public static string function.

Answer №1

Let's break down the process step by step.

Firstly, there is no need for setting submit behaviour to false as we are using a regular button.

The button markup should look like this:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click" />

When the above button is clicked, the code behind function btn_del_Click will be executed.

To add an additional client-side check before executing the code behind function, use OnClientClick.

You can incorporate a confirm dialog in JavaScript to allow or prevent the execution of code behind based on user input.

Your updated button markup with a confirmation prompt would be:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click"
OnClientClick="return myprompt()"
CssClass="btn" />

<script>
function myprompt() {
    return confirm("Really delete this?")
}
</script>

If the user confirms deletion by clicking "OK," the code behind will execute. If they click "Cancel," it will not.

Consider enhancing the default browser dialog appearance by utilizing jQuery.UI for a more polished and customizable experience.

Modify the button markup when incorporating jQuery.UI:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click"
OnClientClick="return myprompt(this)"
CssClass="btn" />

<script>
mypromptok = false
function myprompt(btn) {
    if (mypromptok) {
        return true
    }
    // open jQuery.UI dialog
    var mydiv = $("#mydeldiv")
    mydiv.dialog({
        modal: true,
        appendTo: "form",
        title: "Delete Hotel?",
        closeText: "",
        width: "400px",
        position: { my: 'left top', at: 'right bottom', of: btn },
        buttons: {
            ' ok ': function () {
                mypromptok = true
                btn.click() //trigger button click event again
            },
            ' cancel ': function () {
                mydiv.dialog('close')
            }
        }
    });
    return false
}
</script>

<div id="mydeldiv" style="display:none">
    <h3><i>Delete this Hotel</i></h3>
    <h4><i>This action cannot be undone</i></h4>
</div>

By implementing these changes, a sleek jQuery.UI dialog appears near the button click location, providing a modern feel to the interaction.

These concepts can also be applied to scenarios involving grids and multiple row operations with deletes.

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

Transitioning JS/CSS effects when the window is inactive

My latest project involved creating a small slider using JavaScript to set classes every X seconds, with animation done through CSS Transition. However, I noticed that when the window is inactive (such as if you switch to another tab) and then return, the ...

Ways to evaluate the amount of traffic on a webpage?

Recently, I encountered an issue while creating a page to showcase blog posts. Each post had the typical social media share buttons like "Facebook like," "tweet this post," and "+1." Additionally, there were some extra JavaScript functions added for variou ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

Enhancing jQuery AJAX Performance with Promises and Deferred Objects for Seamless Callback Management

Consider this scenario: Checking the stock availability of a product multiple times in an ecommerce-script. Initially, I implemented it as follows: var checkStock = function(id) { $.ajax({ type: "POST", dataType:'json', url: "class ...

Passing arguments inside the source attribute of an image or link tag in Node.js and

As a beginner in NodeJS, I am facing an issue with passing arguments inside links and image sources. In my template.html file, I have included various scripts and elements to create a search form. The issue arises when I try to incorporate values from the ...

The data in AngularJS is not being successfully incorporated into the service

Utilizing angularjs and ajax, I am attempting to retrieve data from a webservice and pass it to the controller. To accomplish this, I am using a holder (a factory method or service). The setup works fine without the webservice, but when trying to fetch dat ...

Exploring Codeigniter's search feature with pagination

Incorporating search with pagination has been successfully implemented. The controller function is as follows: public function search() { if($_POST) { $search_name=$this->input->post('search_name'); ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

When using AngularJS, encountered an issue where a view was not updating with new data from a $http request

When making a request to the 500px API using $http for popular photos, the response object is successfully returned. However, I am facing difficulty in pushing the retrieved photo items to the view. Below is my current controller code: meanApp.controller ...

Adding a prefix to all specified routes in Express.js

Imagine having an Express app defined in a file called server.js as follows: const app = express(); app.use('/foo', foo); app.use('/bar', bar); module.exports = app; You then import this Express app into another file named index.js: ...

How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an & ...

Making a Chrome extension that allows for cross-domain jQuery.Ajax requests

Looking to develop a Google Chrome extension that displays a notification based on the result of an Ajax request. I have already created the function for generating notifications, all that's left is to make the Ajax request to fetch a .php file from ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

React-Bootstrap Table Toolkit Encounter Search Import Issue

I encountered an issue while trying to integrate React Bootstrap Table into my project, resulting in the following error message. Uncaught ReferenceError: arguments is not defined at Object../node_modules/react-bootstrap-table2-toolkit/lib/src/search/Sea ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

AngularJS ng-include nested form configuration

My application utilizes nested ng-includes. The outer include is a login screen for one application while the inner ng-include includes two templates. The login screen is designed in two steps where the email is checked first and then the password entered. ...

Achieving proper functionality of additional directives within uib-tab components

How can I utilize a callback function for uib-tab directives to refresh inner directives after tab rendering? I'm troubleshooting an issue with a third-party directive when used within the uib-tab directive from angular-bootstrap. The specific direct ...

Retrieving various checkbox values through Ajax

Having trouble retrieving multiple values from checkboxes using Ajax. I am able to get the value of one checkbox but unable to retrieve multiple values. <input name="p_flatform" class="p_flatform" type="checkbox" value="1">Iphone <input name="p_f ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Discovering the Browser Refresh and Close Events in Angular JS: A Comprehensive Guide

Hello, I've attempted using the event below to detect something, but occasionally it doesn't trigger when closing the tab or browser. $window.addEventListener('beforeunload', function(event) { // Your code here }); ...