After pressing the ASP.NET button, the JavaScript function is called followed by the C# function being executed

There is an issue that I'm facing:

I have developed an ASP.NET page which includes an Update panel with an ASP.NET control.

I have a JavaScript function for validation. When the button is clicked, I want to use onclientclick to trigger the JavaScript validation function first and then call the event click button function from code behind.

I have tried several methods but none of them seem to work for me.

Below is a snippet of my code where after clicking the button, onclientclick triggers the JavaScript function for validation, and if the validation passes, it should call the onclick event.

.................... java script function ........................

    <script type="text/javascript" >

function add(){
 if (tag == trye) {


                         document.getElementById('<%=btnInfor.ClientID%>').click();
                         alert("DataAdded")



                    }
                    else {

                          alert("Requiered Field Missing.")
                        return false;
                     }
}

</script> 
.....................
ASP.NET button
...................
<asp:Button ID="btnInfor" runat="server" Text="Add Information" Style="position: absolute;
                top: 1659px; left: 433px;" 
                onclientclick="JavaScript: return myAdd()" />
....................
code behind in C#
......................
 protected void btnInfor_Click(object sender, EventArgs e)
        {    
                \\mycode
}

Answer №1

There might be a problem with the current setup where the javascript function keeps getting called instead of reaching the intended server side method.

To resolve this, first set up the server-side click event handler:

<asp:Button ID="btnInfor" runat="server" Text="Add Information" Style="position: absolute;
            top: 1659px; left: 433px;" OnClick="btnInfor_Click"
            onclientclick="JavaScript: return myAdd()" />

Next, ensure that your JavaScript function returns true in the correct branch:

function add(){
    if (tag == trye) {
        alert("DataAdded");
        return true; 
    }
    else {
        alert("Required Field Missing.");
         return false;
    }
}

Answer №2

There are 2 obstacles that could be hindering the execution of the C# code:

  1. In order for the C# code to be triggered, the Javascript function must include return true; following the line alert("DataAdded")
  2. To activate your C# event handler, you must connect it by adding an attribute to the button, such as...OnClick="btnInfor_Click"

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 is the best way to access the child component in React?

const navArr = [ { path: "/introduction", title: "회사소개", subTitle: [{ title: "summary" }, { title: "vision" }], }, ] {navArr.map((obj) => { return ( <NavItem> ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

Sorry, the provided text is already unique as it is an error message

I'm currently using the react-highlight-words package to highlight text inputted into a textbox After checking out the react-highlight-words documentation, I noticed that they are using searchWords as an array. https://www.npmjs.com/package/react-high ...

What's the best method for securely handling user input containing iframes from a WYSIWYG editor?

I have implemented a feature using the TinyMCE WYSIWYG editor that allows users to input rich text content. Users have the ability to paste links to rich media in the editor, which automatically detects and creates an iframe display. This means that pastin ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...

Tips for updating multiple fields in Prisma ORM

Is there a way to upsert multiple fields in Prisma ORM using just one query? I'm looking for a solution that allows me to upsert all fields at once, without having to do it individually. Is this possible? ...

"Click events on jQuery's cloned elements are not retained when the elements are removed and appended to a container for the second time

Take a look at this fiddle: https://jsfiddle.net/L6poures/ item.click(function() { alert("It's functioning") }) $("#container").append(item) var stored = item.clone(true, true) function add_remove() { $("#container").html("") $("#conta ...

Identifying with a jQuery IF statement all input fields that contain null values in order to eliminate the respective elements

My goal is to create a jQuery script that checks all input fields to see if they are empty. If an input field is empty, I want to remove the child image of the next occurring span element. Here is what I have attempted so far: if ($("input").val() == "") ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Having trouble implementing a cookie on the second domain using the first domain. Can't seem to get it to work properly

Currently, I am working on integrating ajax functionality with PHP. My main objective is to generate a cookie on the page where ajax call is made. The scenario involves two distinct domains - domain1.com and domain2.com. Essentially, the ajax code is imple ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

Enhance your website with the latest jQuery plugins and CSS

Currently, I am utilizing jQuery to develop plugins for my application. It is worth noting that each plugin demands a distinct CSS file. What approach should I follow to effectively load both the jQuery file and the respective CSS? Moreover, the plugins ...

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

The Dropdownlist fails to activate the SelectedIndexChanged event

I am encountering an issue with my dropdownlist (dr1) that is supposed to trigger the update of dr2 without affecting dr3. The problem lies in the fact that dr1 triggers the update, but does not enter into dr1_SelectedIndexChanged as expected. This can be ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...

Issues with angular-strap popover's onBeforeShow function not functioning as expected in Angular

I am currently utilizing the angular-strap popover feature. To learn more about it, visit According to the documentation, when an onBeforeShow function is provided, it should be called before the popover is displayed. However, I am experiencing issues wit ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...