Automatically calculate the product of two columns in a gridview

Greetings,

I am currently working on a project that involves calculating values from two textboxes within a gridview and displaying the result in a third textbox using JavaScript. The calculation should occur as soon as a value is entered into the second textbox.

The textboxes in question are Quantity and Price, with the desired result being displayed in Total.

To achieve this, I have attempted the following approach:

protected void gvPOItms__RowCreated(Object sender, GridViewRowEventArgs e)
{
    try
    {            
        TextBox txt1 = (TextBox)e.Row.FindControl("txtQty");
        TextBox txt2 = (TextBox)e.Row.FindControl("txtRate");
        TextBox txt3 = (TextBox)e.Row.FindControl("txtValue");

        txt1.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
        txt2.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
    }
    catch (Exception ex)
    {
        Response.Write(ex);
    }
}

In the provided JavaScript function, the logic for the multiplication of the input values is expected to be executed, resulting in the calculated total displayed in the designated third textbox.

Despite implementing the aforementioned code snippets, I am encountering difficulties in obtaining the desired outcome without any error prompts.

If anyone can provide insight into what may be causing this issue, I would greatly appreciate it.

Answer №1

It is important to convert string to int before performing multiplication when dealing with textbox values.

Here is a suggested code implementation:

txt1.Attributes["onKeyup"] = "javascript: return multiplyValues('" +  Convert.ToInt32(txt1.Text) + "','" +  Convert.ToInt32(txt2.Text) + "','" +  Convert.ToInt32(txt3.ClientID) + "')";
txt2.Attributes["onKeyup"] = "javascript: return multiplyValues('" +  Convert.ToInt32(txt1.Text) + "','" +  Convert.ToInt32(txt2.Text) + "','" +  Convert.ToInt32(txt3.ClientID) + "')";

Within the script:

<Script type="text/javascript">
 function multiplyValues(Qty,Rate,txt3)
    {
    //Perform multiplication operation

    document.getElementById(txt3).value=Qty*Rate;       
    }
</script> 

Answer №2

Here is a solution for the issue with this code snippet

txt1.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
txt2.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";

Instead, you can use the Add method like this:

txt1.Attributes.Add("onKeyup", "javascript: return multiplication('" +
     txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')");
txt2.Attributes.Add("onKeyup", "javascript: return multiplication('" +
     txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')");

Additionally, remember to include parseInt() in your JavaScript code like so:

var Qty  = parseInt(document.getElementById(txt1).value);
var Rate = parseInt(document.getElementById(txt2).value);

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

Accessing Angular templates scope after the document is ready using angular.element()

I am currently learning Angular and experimenting with the Symfony2 + AngularJS combination. I am facing a specific issue that I need help with: Within my index.html file, I have the following script: <script> global = {}; $(document).ready ...

Ways to prevent images from vanishing when the mouse is swiftly glided over them

Within the code snippet, the icons are represented as images that tend to disappear when the mouse is swiftly moved over them. This issue arises due to the inclusion of a transition property that reduces the brightness of the image on hover. However, when ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

Ways to conceal all components except for specific ones within a container using JQuery

My HTML structure is as follows: <div class="fieldset-wrapper"> <div data-index="one">...</div> <div data-index="two">...</div> <div data-index="three">...</div> < ...

How to efficiently manage drop-down menus on a website using VBA specifically designed for Internet Explorer

I am a beginner in VBA and coding, seeking assistance from the community. The purpose of this VBA code is to automate the following steps: Open Internet Explorer Enter user ID and password to login Select the current date Select a specific option (X1) fr ...

extracting the HTML content from JavaScript and saving it into a standalone file

update When I click a link, a popup opens and I see all this HTML. The smile method is called when I click the link, and we append HTML in that method so that we can see it when the popup is opened. I moved it to a separate file something.component.html, ...

Unraveling the Layers: Exploring Zip Entries Within Nested Zip Files Using C# or VB.NET

Although there is a solution for this problem using the Java libraries (Read a zip file inside zip file), I have been unable to locate any examples in C# or VB.NET. For a project with a client, I need to utilize the .NET 4.5 ZipArchive library to navigate ...

The issue with Internet Explorer failing to adhere to the restrictions set on maximum width and

I'm attempting to scale my images precisely using CSS: HTML: <div id="thumbnail-container"> <img src="sample-pic.jpg"/> </div> CSS: #thumbnail-container img { max-height: 230px; max-width: 200px; } In this scenario, ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

Leverage environment variables in React JS to define distinct API URLs for production and development environments

For my React app, I started with create-react-app as the boilerplate. To make a request to my local server, I'm using fetch. fetch("http://localhost:3000/users") .then(function(res){ return res.json() }) .then(function(res){ return res.data }) ...

Managing spinners in Protractor when they are concealed by a wrapper element

While writing a test for an Angular app using Protractor, I encountered several issues with handling spinners. I managed to solve some of them, but I'm unsure how to test spinners that are hidden by a wrapper. For instance, when the parent tag has ng- ...

What are the steps to redirect from a nested route back to the top route using Node.js with Express?

Is there a way to redirect from a nested route to a top route in Express.js? In the following code snippet, how can we make the callback for the route /toproute/nested redirect to /profile instead of /toproute/profile? // app.js const express = require(& ...

Clicking on the ActionButton will trigger the sending of an HTTP Request in this Firefox

Seeking guidance: As I develop an addon, my objective is to initiate a HTTP request upon clicking the ActionButton. The data to be sent to the server includes the URL of the tab and the content of the page. Initially, I attempted to create a log message a ...

Monitoring the validity or errors in AngularJS input fields

I'm attempting to observe the $error or $valid status of a control. Here is the control in question: <form id="myForm" name="myForm"> <input name="myInput" ng-model="myInputMdl" business-validation/> </form> The business-validat ...

Incorporating map() with data passed down as props from App.js into child components

I have React version 18.2 and I want the child component in App.js to receive data and utilize the map() function. Although the child component successfully receives the data, it is encountering an issue when trying to use map(). An error message is disp ...

Displaying the saved MTRC (markdown-to-react-components) content from the database

I currently have data stored in a database that has been produced using the markdown-to-react-components package as MTRC(content).tree What is the best way to render this content? I've experimented with various approaches, such as dangerouslyInsertHT ...

Ways to modify React icons upon clicking them?

Dealing with some icons from react-icons that seem to be causing trouble. Whenever I try to change an icon from outline to filled upon clicking, all the icons end up changing together. It's not functioning as expected. Take a look at my code snippet ...

Looking to display a page header alongside an image on the same page

I'm currently learning React.js and working on my very first app. As someone new to frontend development, I am aiming to have a header design similar to that of popular websites like StackOverflow or YouTube, where an image or icon is positioned just ...

Sort an array of objects by matching string properties with elements from another array

If the array of objects is represented by rows and wantedBrands consists of an array of strings, how can I achieve a specific result? let rows = [ { name: "Russia", brands: ['XM1', 'XM2', 'XM3'] }, ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...