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

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...

Struggling to align the push menu properly within the Bootstrap framework

I am currently utilizing Bootstrap as my UI framework and attempting to create a push menu on the left side of the page. While I have made progress towards achieving this goal, there are some bugs in the system that I am encountering. Specifically, I am ha ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

Activate response upon verifying website link

I am adding functionality to my HTML page where I want certain sections to be visible when the user clicks on a link. Initially, these sections are hidden using the CSS property display: none;. My aim is to make these sections visible when the user clicks ...

Is GetStaticPath in NextJS suitable for generating large amounts of static data?

On my website, I have a page dedicated to displaying information about hotels based on their unique IDs. To achieve this functionality, I utilize getStaticPath to generate paths like /hotel-info/542711, where 542711 represents the hotel's ID. However ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Is there a way to ensure that the code only runs if the promise has been successfully fulfilled

In my NodeJS project, I am leveraging promises to ensure that the server stops running if certain functions do not meet the required conditions. Currently, the server halts as intended, but I also want to include a console log message when the promises are ...

JavaScript code to locate the most pertinent strings within an array based on a specific substring

I'm working with a large array containing names of people, such as: let names = [ "John Brown", "Tristan Black", "Carl Jobbs", "Aidan Burrows", "Taylor Joe" ]; When given an input, I want to return the top 5 most relevant results ...

Having trouble uploading images from my personal computer onto Phaser 3

Currently in the process of coding a game for a school project using Phaser. I am quite new to Phaser and have very little knowledge of JavaScript. Despite searching online for potential solutions, none seem to be effective for me. I have included my cod ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application: <div id="app"> <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button> <div v-if="isLoading">Lo ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

Tips for managing state updates in React Redux

Currently, I am utilizing a reducer to manage the state in Redux. The current structure of my state is as follows: { activeConversation: "Jim" conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] user: {id: 8, username: &quo ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Is there a way to implement word wrapping in li text without making any changes to its width

Is there a method to wrap the content inside li elements without modifying their width? As an illustration, consider the following structure - <ul> <li>Text Example</li> <li>Text Example</li> <li>Text Exampl ...

Allow the json array to be transformed into a format suitable for input

Hey there, I've received a JSON array as the response of my ajax request: {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05" :0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}} Now, I'm looking to create a chart using the ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

What is the standard text displayed in a textarea using jQuery by default

My goal is to display default text in a textarea upon page load. When the user clicks on the textarea, I want the default text to disappear. If the user clicks into the textarea without typing anything and then clicks out of it, I'd like the default t ...