Perform dynamic calculations in a ASP.NET repeater using Javascript

Within a repeater item, I am dealing with two textboxes. The goal is to perform some processing on a value entered into one textbox and then display the result in the other textbox when the user leaves. Ideally, this needs to be handled client-side.

My JavaScript knowledge is limited, but so far I have managed to come up with:

<asp:TextBox ID="txtMarkup" runat="server" onblur='calculateValues(this,"txtPercentage")'></asp:TextBox>
<asp:TextBox ID="txtPercentage" runat="server" onblur='calculateValues(this,"txtMarkup")'></asp:TextBox>

//Some code

<script type="text/javascript">
  function calculateValues(sender, target) {
    //Perform calculations
    var parent = sender.parentNode //get the container, so I can get the appropriate target
    //This is where I'm having trouble
  }
</script>

I am struggling to identify how to locate and update the other textbox with the processed value. Additionally, I am unsure if this approach is the most efficient, and I am willing to consider alternative solutions.

*EDIT

After exploring different methods, I finally achieved the desired functionality using a new technique. For those seeking a similar solution in the future, I have shared it as an answer below.

Answer №1

To access the inputs, you can utilize their tagname and then extract them from the returned collection:

var input1 = parentElem.getElementsByTagName('input')[0];
var input2 = parentElem.getElementsByTagName('input')[1];

A common method I use to incorporate client id in the JavaScript code is:

document.getElementById('<%= clientIdOfInput.ClientID %>').value = 'some value';

If you're working within a repeater, adjustments may be required.

Answer №2

I recently made some changes to my problem-solving approach, which led to successful resolution. Below is the VB code I utilized, but it can be easily translated to other languages. The ClientIDModes are all configured as "Inherit."

Here is the Markup:

<asp:Repeater ID="rptEstimateDetails" runat="server">
    <ItemTemplate>
        <asp:TextBox ID="txtPprPriceDtlQuoted" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtPprPriceDtlMarkup" runat="server"></asp:TextBox>
    </ItemTemplate>
</asp:Repeater>

<script type="text/javascript">
    function CalculateValues(sender, target) {
        //Sender & Target come in pointing exactly where they need to be
        //Perform calculations
        document.getElementById(target).value = //Calculated value
    }
</script>

And here is the Code-Behind:

Private Sub rptEstimateDetails_ItemCreated(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptEstimateDetails.ItemCreated    
    Dim quoteTxt As TextBox = e.Item.FindControl("txtPprPriceDtlQuoted")
    Dim markupTxt As TextBox = e.Item.FindControl("txtPprPriceDtlMarkup")
    Const prefix As String = "MainContent_rptEstimateDetails_"

    quoteTxt.Attributes.Add("onblur", "Javascript:CalculateValues('" & prefix & quoteTxt.ClientID & "', '" & prefix & markupTxt.ClientID & "');")
    markupTxt.Attributes.Add("onblur", "Javascript:CalculateValues('" & prefix & markupTxt.ClientID & "', '" & prefix & quoteTxt.ClientID & "');")
End Sub

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 every single .json file present in a specific folder

I'm working on developing an Android app that utilizes JSON data. Is there a method to establish a directory structure similar to this: http://......./jsons/*.json Or is there another way to append additional data into a JSON file (such as a.json) a ...

Experiencing difficulties with ng-modal in the controller invocation

These are the steps I followed: 1) First, I downloaded the script file from: https://github.com/doodeec/dcom-angular-dialog 2) Next, I included it in both my webpage and application: var summariesApp = angular.module('summariesApp', ['ui ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

Taking pictures on my website with the help of c#, HTML (excluding HTML 5), and javascript

My current project requires me to capture an image from a webcam, and I have been brainstorming solutions. However, there are specific conditions that I must adhere to in order to achieve the desired result: I am unable to utilize HTML5 due to compatibil ...

Having trouble with your custom accordion content in React JS not sliding open?

Check out my progress so far with the fully functioning view here This is the structure of the Accordion component: const Accordion = ({ data }) => { return ( <div className={"wrapper"}> <ul className={"accordionList ...

Ways to verify various values in the toBe function

I'm currently testing to ensure that all the links display the correct text. I am specifically checking for two values: "enable" or "disable". expect(toggleName).toBe('Disable'); Is there a way to check for multiple values, such as 2 or mo ...

Discovering the Perfect Cube Using Factorization Technique

Looking for some guidance on a C/JS program to find perfect cubes using the factorization method below. Any assistance is greatly appreciated. 3 * 3 * 3 3 * 3 * 3 3 * 3 * 3 JavaScript Code var num=19683; var arr=[]; for(i=2;i<num;i++){ if(nu ...

Step-by-step guide on placing a geometry shape precisely at the mouse click location using ThreeJS

I'm attempting to create a circle in the exact position where the mouse is clicked, but the circle ends up being drawn slightly off. Can anyone pinpoint what needs to be adjusted in the code below? var camera = new THREE.PerspectiveCamera ...

Supervising ongoing asynchronous tasks within Node.js's promise-based ecosystem

In my Node.js application, I have created a reliable robot program that continuously sends requests to an API. I have taken precautions by handling errors and setting timeouts for promises in order to prevent any issues from occurring. Now, I am looking t ...

Avoiding JavaScript onclick event using JSON information

Here's a situation I'm dealing with: I have a button created using PHP that triggers a JavaScript onclick event: <button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php e ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

What is the best way to conceal a section of a div using CSS/React?

I am attempting to create a design where the entire content of a div is displayed initially, and then after clicking a button labeled "show less", only 300px of the content will be shown with the button changing to "show more". <div className="bod ...

JS switch for numerous container elements

How can I create a toggle slider in HTML for multiple elements displayed using foreach? Each element should open a div block with specific information and have a close button. Unfortunately, I haven't been able to find any suitable code to achieve thi ...

Adding a column to aspnetuser: A step-by-step guide

I am currently working on a project that involves two separate databases. The first database contains tables for aspnetusers, roles, logins, and related data, while the second database houses the rest of the information. I am looking to implement a system ...

Unable to determine the success of testing my catch block within the then clause

I'm a beginner in unit testing code and feeling a bit lost! I am attempting to throw an error for the function below to cover the catch block, but so far I have not been successful and I am not sure why. Function: public initialize(): Promise<thi ...

Adjusting the selected state of an HTML/CSS checkbox with JavaScript

After downloading a theme with a tailored switch component that replaces the standard checkbox functionality, I noticed that the 'checked' status of the underlying checkbox does not change upon click or touch events. Here is the HTML structure: ...

Numerous clocks on display

I am trying to display two clocks on my webpage, but for some reason only one clock is showing up. The first clock script is as follows: <script type="text/javascript"> var tmonth=new Array("January","February","March","April","May","June","July"," ...

Issue: My application is unable to start due to the module nuxt.js not being found. Can someone help me troubleshoot

Upon attempting to execute npm run dev following the installation of dependencies, I encountered an error that has left me puzzled. Despite trying various solutions found online, none have seemed to resolve the issue. <a href="/cdn-cgi/l/email-protectio ...

The React ternary operator within HTML does not display the correct HTML output

I'm currently learning React and facing a challenge with using a ternary operator. My goal is to display a minus sign by default, and then switch it to a plus sign when clicked. I implemented the ternary operator in my JSX and set the initial state of ...

Ensuring the accuracy of a condition within an HTML form through the utilization of

I am interested in designing an HTML page that includes a small form. The form should include: Name Gender Date of Birth "I Agree" checkbox Submit button One important condition to note is that if the individual's age falls between 20 and 25 (calc ...