Ways to create and run an ASP.NET text change event handler using both JavaScript and code behind

On my net website, I have a textbox control inside a datagrid control.

I am interested in implementing a textchange event in JavaScript that will calculate the sum of the values inside the textboxes in the datagrid and display that addition in a label outside the grid.

In addition to the client-side calculation, I would also like to perform the same addition in the codebehind file (*.cs).

However, I want the codebehind logic to only execute if the browser does not support JavaScript. This means that when JavaScript is supported, only the client-side script should run and the server-side code should be bypassed.

Answer №1

Have you implemented the textboxes as EditItemTemplate in your code? If so, make sure to include the OnTextChanged event - Textbox1_OnTextChanged within the textboxes in the EditItemTemplate.

<asp:DataGrid ID="Grid" runat="server">
        <Columns>
            <asp:TemplateColumn>
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" OnLoad="TextBox1_Load" OnTextChanged="Textbox1_OnTextChanged"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>

To calculate the sum of values on the server side, ensure that you also add the Load event (Textbox1_OnLoad) in the EditItemTemplate for the textbox. This will bind the clientside event of the text box properly.

 protected void TextBox1_Load(object sender, EventArgs e)
    {
        TextBox newTb = sender as TextBox;
        if (newTb != null)
        {
            newTb.Attributes.Add("onChange", "sumup(this)");
        }
    }

Using Javascript, you can handle the sumup event and retrieve the values of the textboxes using the this object to perform addition operations. Remember to return false at the end of the sumup function to prevent postback if the javascript support is enabled.

In case javascript support is disabled, the method will not be executed, and the postback will occur automatically.

We hope these steps provide a clearer understanding of how to achieve the desired functionality.

Best Regards,

Lakxman Kumar C

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

Tips for identifying the IP address of clients visiting or logging into our website

Hey there, I'm facing a minor issue in trying to determine the IP Address of the client accessing my website. Despite numerous attempts, all I keep getting is 127.0.0.1 as the IP address while testing on localhost. If anyone could kindly share a code ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

The unexpected outcome of ambient light in Three.js

Within the code snippet below, I am displaying some cubes and illuminating them with a PointLight and AmbientLight. Strangely, when the AmbientLight is set to 0xffffff, it changes the side colors to white regardless of their assigned colors. The point ligh ...

Excessive calls to the component update in React with Javascript are leading to application crashes

componentDidUpdate() { // Retrieving trades from the database and syncing with MobX store axios.get(`http://localhost:8091/trade`) .then(res => { this.props.store.arr = res.data; }) } After implementing this code, my ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...

Combining a variety of animations within a mesh

Can someone help me understand this specific example in Three.js? The link is . I am facing some difficulties with the BlendCharacter.js file. this.load = function ( url, onLoad ) { var scope = this; var loader = new THREE.JSONLoader(); load ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

One way to restrict user input to only minutes in the time input field

Is there a way to implement time control that only accepts time values? For example, when entering 00:15, it automatically converts to 00 to 12. Can we ensure that only time formats are accepted? Alternatively, can we use input type="text" and re ...

Leveraging async/await to handle the insertion of SQL data

function Scan_Insert_Recursive (dir_path) { //scans dir_path recursively and inserts file path into a temporary list Scan_Recursive(dir_path, (err, files) => { //using npm recursive_readdir for scanning if(err) { console.log(err) ...

Issues arise when trying to access JSON data that has been added to an array using the JavaScript .push method

I am encountering an issue where I cannot retrieve values from an array after storing it in a variable outside of the getJSON function. The response in JSON format looks like this: [ { "Book_ID": "1", "Book_Name": "Computer Architectu ...

When Mui Select is used with grouping, it automatically selects the first option as the default

When Mui Select with grouping is first rendered, it automatically selects the first option, which may seem strange. const generateOptions = useCallback((options: ISelectOption[]) => { return options.map((opt, ind) => { if ...

"By implementing an event listener, we ensure that the same action cannot be

function addEventListenerToElement(element, event, handlerFunction) { if(element.addEventListener) { element.addEventListener(event, function(){ handlerFunction(this.getAttribute("src")); }, false); } } //initialize the function addEve ...

Picture fails to load on Ionic app on the device

Currently, I am utilizing Ionic 3 for my project. The location of the images file is \src\assets\img. This pertains to a basic page implementation. export class BasicPage { items = []; constructor(public nav: NavController ,private adm ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Refreshing the current checkbox input field in React

I developed a unique custom weekdays check input field using React.js to display which days are open for customers. By looping through a hardcoded array, each day is rendered with its corresponding input checkbox. The first row shows Monday through Thursda ...

Script for migrating MongoDB attributes to an array

I am in the process of creating a database migration, and the current structure is as follows: { "site" : { "name" : "siteName1" }, "subStages" : [ "subStage1", "s ...

Oops! Looks like there was a syntax error with the JSON data at position 1. This resulted in a 400

Having issues submitting form data in my Vue app with an express backend API. The endpoint works fine on postman but I keep getting errors like "SyntaxError: Unexpected token g in JSON at position 0" or "400: Bad Request." I've tried using JSON.parse ...

implementing multiple updates in Mongoose for MongoDB

There are often times when I need to make multiple update requests based on various conditions. if (some true condition) { let recordBeforeUpdate = await this.PatchModel.findOneAndUpdate({ "_id": patchId }, { $inc: { inStockPallets: -1, f ...

Is it possible to delay the postback by 3 seconds?

I am working on a usercontrol that contains multiple dropdown lists and a button. When the user clicks the button, I need it to redirect based on the selections in the dropdown lists. Instead of immediately redirecting, I would like to show a loading icon ...