What are the various ways to trigger JavaScript functions in different events?

Seeking help with calling a specific JavaScript function in an ASP.NET page. The code for the function is as follows:

<script type="text/JavaScript">
function CalculateDistance (plat1, plon1, plat2, plon2) 
{
   try
   {  
       :
       :
       var d = R * c;

       return d;
   }
   catch (error) 
   {
           alert(error);
   }
}
</script>

I need to understand how to invoke this JavaScript function both on page load and button click events while capturing the return value, specifically the distance calculated based on four input parameters.

Your assistance would be greatly appreciated!

Best regards, Girish

Answer №1

For triggering a function on page load, you can use:

<body onload="CalculateDistance(...);">

If you want to call a function on the click event of a button, you can try this:

 <asp:Button ID="btn" Text="Save" runat="server" OnClientClick="CalculateDistance(...); return false;" />

To capture the return value, utilize a hidden field control:

 <asp:HiddenField ID="hdn" runat="server" />

You can store the return value of the javascript function in this hiddenfield by following these steps:

<asp:Button ID="btn" Text="Save" runat="server" OnClientClick="document.getElementById('<%= hdn.ClientID %>').value=CalculateDistance(...); return false;" />

Answer №2

In my understanding, it is not possible to directly return a value from JavaScript to the server side. It would be more appropriate to implement this functionality on the server side itself.

However, there is another approach you can take by utilizing a hidden field. You can store the desired value in a hidden field using a JavaScript function and access it on the server side as needed.

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

Issue with Vuejs/Laravel computer function bug

Trying to figure out how to calculate the Total Tax Amount after an input using Vuejs in a Laravel application. The function on my computer that is supposed to calculate the total isn't working as expected. Can anyone spot where the issue might be? H ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Is Node.js categorized as multithreading due to its utilization of worker threads?

Throughout my life, I was under the impression that Node.js and JavaScript operated as a single threaded language. It was always said that Node.js wasn't ideal for CPU intensive tasks due to its single threaded nature. Multithreading, on the other han ...

Injecting styles into an iframe using Javascript in a vue.js environment

When working within the admin area of a website builder, I aim to provide users with a visual preview of style changes before they save any updates. To achieve this, I use an iframe to display the user's website, allowing for visual adjustments to be ...

Troubleshooting Azure SDK: Tips for Displaying the Appropriate REST API

Currently, I am utilizing the Azure JS SDK to interact with Postgres in Azure using various modules such as @azure/arm-postgresql, @azure/identity, and @azure/functions. My main goal is to access the underlying REST Api for debugging purposes. For instanc ...

What is the process for creating an xpath for hyperlinks with the 'contains text' attribute?

I am in need of creating Xpath for links based on contained text. I have devised the following code to achieve this, however, a scenario arises when there are three links named 'Entity', 'Entity Type', and 'Entity Group'. If I ...

Different types of arrays suitable for the useState hook

I have a scenario where I am utilizing setState to assign an array of objects. Here is the code snippet: const [friendList, setFriendList] = useState<any>(); const _onCompleted = (data: any) => { let DATA = data.me.friends.map( (item ...

AngularJS property sorting: organize your list by name

I have a complicated structure that resembles: { 'street35':[ {'address154': 'name14'}, {'address244': 'name2'} ], 'street2':[ {'address15& ...

Using Knockout to bind an element to the selected value from a dropdown list

When using the following select, I am connecting it to an observable array. <select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???&a ...

Order of execution in Single Page Applications when using multiple files: understanding the Javascript async defer concept

I am currently working on enhancing the performance of my webpage, which is built using EmberJS. One strategy I'm considering is utilizing `asyc` and `defer` attributes for our Javascript files. I have already implemented other optimizations such as ...

The Super expression in Node.js can only be null or a function

When working in my UserService class, I attempted to use the super keyword to call my base class constructor. However, I encountered an error message stating: TypeError: Super expression must either be null or a function Below is the code for my UserServi ...

The server is currently unable to process my JSON object

I'm encountering an issue with my AJAX program not accepting the JSON object that I am trying to pass. I have an MDF file accessed by registerdb which I believe is accurate. It contains 3 columns: ids, username, and password filled with data. Any as ...

Combining JavaScript files can cause conflicts with duplicate identifiers when using Typescript namespaces

As a newcomer to Typescript, I am grappling with the concept of namespaces and how to reference Interfaces that are defined in separate files. Coming from a .NET C# background, I am used to creating each class and interface in their own file. INationalRai ...

Combining multiple rows into one using either mysql or lodash was achieved by Node

Currently in my Javascript framework, I am utilizing the Node MySQL library for executing MySQL queries. I encountered an issue with a left join that resulted in multiple rows being returned. This is because the left join generates duplicate rows with diff ...

Best practices for utilizing an enum in JavaScript objects

In the past, I would create classes with a type property in traditional OOP languages such as Swift or Java: struct ClassA { enum Type { case b, c, d } var type: Type } and then use it like this: let a = ClassA(type: .b) In ES6, a ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

JavaScript events are failing to trigger within the content area of an iframe

When attempting to run a given example by double clicking inside the content area of an iframe, the clicks and any JavaScript events are not being fired. Currently, the events can only be triggered by clicking on the border of the iframe, not inside the ...

Ways to alter the appearance of individual characters in the text input

My latest project involves dynamically changing the CSS styles of each individual character in a given text input. For example, if the user types "Stack" into the input field, I want the 'S' to appear in red, 't' in blue, 'a' ...

Would it be unwise to implement a CustomEvent in a React global component, such as a snackbar placed in the AppRoot?

I am in need of a global notification handler similar to a snackbar that can be triggered from any part of the project, not just a react component. My solution was to create a component that listens for a CustomEvent and displays the snackbar when the eve ...

Issue: The variable '$viewMap[...]' is either null or undefined

Unfortunately, my knowledge of jQuery/Javascript is quite limited. I am encountering a Javascript error when trying to change the "how did you hear about us" dropdown on a form. The error message states: Error: '$viewMap[...]' is null or not an ...