Executing a Javascript function on the server side with ASP.NET

I have a Textbox within a GridView. I am trying to update the Label.Text when the text in the Textbox is changed. However, I am facing an issue with calling a JavaScript function written in the .cs code behind file. Can anyone spot any mistake in the TbUnitCost_TextChanged method?

This is my ASPX page:

<ItemTemplate>
  <asp:TextBox Style="text-align: right" ID="TbUnitCost" runat="server" Width="80px" Text='<%#Bind("Unit_Cost")%>' AutoPostBack="true" OnTextChanged="TbUnitCost_TextChanged"  TextMode="Number"></asp:TextBox>
 </ItemTemplate>

Code Behind Page looks like this:

 protected void TbUnitCost_TextChanged (object sender, EventArgs e)
    {
        GridViewRow currentRow = (GridViewRow)((TextBox)sender).Parent.Parent;
        int rowNo = currentRow.RowIndex;
        string gridName = "GridWorkExpenses";
        TextBox tbunitCost = (TextBox)currentRow.FindControl("TbUnitCost");
        int row = Convert.ToInt32(tbunitCost.Text);

        tbunitCost.Attributes.Add("onchange","javascript:calculateTotalCost('"+rowNo+"','"+gridName+"');");

    }

The JavaScript function being used is as follows:

<script type ="text/javascript">
    function calculateTotalCost(rowNo, GridName) {                        

        if (GridName== 'GridWorkExpenses') {
            var rowscount = document.getElementById('<%=GridWorkExpensesSheet.ClientID%>').rows.length;
            return calculateTotalUnitCost("GridWorkExpensesSheet", rowscount,rowNo);
        }
   }
 </script>     

Answer №1

Consider employing the following suggestion:

AddScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "CalculateTotalCost", true);

If you encounter any additional issues, please explain them.

Answer №2

Utilize ScriptManager.RegisterStartupScript to load a script dynamically in ASP.NET framework, which allows for client-side script execution.

Another approach

An interesting conversation dating back to earlier times can be found here [1]:Exploring the distinctions between RegisterStartupScript and RegisterClientScriptBlock?

Please make sure to explore this resource as well.

Answer №3

Greetings! Ensure that all commands are combined into a single string.

 ScriptManager.RegisterClientScriptBlock((sender as Control), GetType(), "jQueryCommand", "$('.MenuLoginLink').hide();$('.MenuUsername').show();$('.MenuUsername').text('" + Currentmember.Mobile  + "');$('.MenuExit').show();" +
                " $('.btnLoginInFriends').hide();$('#HiddenSession').val('" + int.Parse(Session["CurrentUserID"].ToString()) + "');", true);

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

The Jsoup function for sending data does not yield any results

Can someone assist me with sending data to a form in this format? <form id="money" action="" method="post"> <input id="user" type="text" placeholder="Username" maxlenght="10" name="user"></input> <div class="select"> <select id= ...

How to set a JSON Schema property to specify the maximum length for a numerical value

I need to limit the decimal Amount field to have a length of 12+4, meaning the maximum integer value can be 999999999999 and the maximum number of fractional digits is 4. I am implementing schema validation using NewtonSoft.JSON. Despite trying the schema ...

Adjusting the display of HTML elements depending on geolocation authorization

I am currently facing an issue with my HTML code where I want to show an element only if the user declines to share their location with the browser. However, my code is not functioning as expected when the user rejects the location request. On the other ha ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Troubleshooting: PHP AJAX Image Upload Issue - Images Not Being Uploaded

I am having an issue with my code. Although it doesn't show any errors in the console, clicking the upload button does not trigger any action. Following a tutorial, I tried to send a post request to itself, but the image is neither uploaded to the des ...

The date entered in an HTML input is being interpreted as "incorrect" by the system

Upon inputting 3/15/2019 as the date and then checking the time with console.log(fromDate), the output appears as Thu Mar 14 2019 19:00:00 GMT-0500 (Central Daylight Time). Why is it not showing Fri Mar 15 2019 00:00:00? Could this be related to the tim ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Implementing external JavaScript files such as Bootstrap and jQuery into a ReactJS application

Just diving into ReactJs, I've got static files like bootstrap.min.js, jquery.min.js, and more in my assets folder. Trying to incorporate them into my ReactJs App but running into issues. Added the code below to my index.html file, however it's ...

The simplest method to make HTML elements inaccessible to the Simple HTML Dom Parser in PHP

Imagine a scenario where a basic web application is running and utilizing Simple HTML Dom Parser. The code snippet below demonstrates this: <?php include('simple_html_dom.php'); $html = file_get_html('http://someurl.com'); ...

Automatically copy any chosen selection on the page to the clipboard

Is there a way to copy any selection from a webpage to the clipboard, regardless of where it is located on the page (div, text input, password input, span, etc.)? I have created a function that can retrieve the selected text, but I am struggling with sett ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Switch the div's class when the parent element is chosen

I have encountered a complex issue involving two problems for which I am unable to find a solution. In the default state without hover or selection, this div displays with a purple border when selected. My concern is: How can I change the class of the ico ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

Switch button for updating text, icon, and displaying search bar

Having trouble with a header and navigation bar setup. The goal is to have a search button that toggles between "Search" and "Close Search" when clicked, while also opening the search bar below the navigation. I've experimented with different methods ...

Unable to showcase information in a jQuery UI popup through AJAX when initially presented

I'm trying to display reviews from my database on a jQuery UI dialog box upon loading, but nothing is showing up. Here are the reviews: {"results":[{"review_text":"good"},{"review_text":"not bad"},{"review_text":"great"}]} Can someone please check m ...

ng-hide is not functioning to display the form

I'm trying to display a form using ng-if when the "add" button is clicked, but it's not working. I've looked at several examples and tried them all, but none have worked for me. Here is the code I am using: angular.module('myFormApp&ap ...

Utilizing Google Script to extract information from Gmail emails and transfer it to Google Sheets

I am facing a challenge with extracting data from an email and inputting it into a Google Sheet. While most of my code is functioning properly, I'm struggling with the regex section due to lack of expertise in this area. Below is a snippet of the HTM ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

Exclude specific tests by default when using MSTest

I need to configure certain tests so that they are not automatically executed when running the dotnet test command. These specific tests should only be run when a parameter is explicitly set by an environment variable or another filter such as test catego ...