What about dynamically generating content with WebUserControl?

I have created a custom WebUserControl with three HTML controls, two buttons, and one input text. Each control has a static ID, which I believe is not incorrect. The control events are set up using JavaScript. After delivering the control to the client, they requested to have five instances of this user control on the same page, each with different parameters for the event. When any event is triggered, it initializes all the user controls since the JavaScript function relies on the TextBox UserID.

Below is the code snippet:

//Markup code in the user control, where each control has a static ID
<input id="Text_Output" type="text" runat="server" onkeypress="return saveValue(event);"    />

<input id="Button_Add" type="button" runat="server" value="ˆ"
    style="width:21px; height:14px;vertical-align:bottom;"   />

<input id="Button_Subtract" type="button" runat="server" value="ˇ" 
  style="width:21px; height:14px;vertical-align:top;"    />

//JavaScript function Add() in the user control
function Add(incValue, percValue) {

var outputValue = document.getElementById('<%=Text_Output.ClientID%>').value;
var incremeantValue = incValue;
var precsionValue = percValue;

if (outputValue.indexOf(".") > 0) {
    var total = (parseFloat(outputValue) + parseFloat(incremeantValue));
    document.getElementById('<%=Text_Output.ClientID%>').value = parseFloat(total).toFixed(parseInt(percValue)).toString();
}
else {
    if (percValue == 0) {
        document.getElementById('<%=Text_Output.ClientID%>').value = parseInt((parseFloat(outputValue) + parseFloat(incremeantValue)).toString());
    }
    else {
        var total = (parseFloat(outputValue) + parseFloat(incremeantValue));
        document.getElementById('<%=Text_Output.ClientID%>').value = parseFloat(total).toFixed(parseInt(percValue)).toString();
    }
}

}




//Markup code used in webpage
//This button will connect(initialize) the events for the user control 
<input id="Button1" type="button" value="button" onclick="IntilizeControl()"  /><br />
<My:UserInfoBoxControl ID="JSNumeric_Control" runat="server" />

//JavaScript InilizeControl() function
function IntilizeControl() {

 var ButtonAdd = document.getElementById('<%=JSNumeric_Control.FindControl("Button_Add").ClientID %>');
//Add(IncrementValue,PrecesionValue)
 ButtonAdd.setAttribute("onclick", "Add(1,1)", '<%=JSNumeric_Control.FindControl("Text_Output").ClientID%>');

var ButtonSubtract = document.getElementById('<%=JSNumeric_Control.FindControl("Button_Subtract").ClientID%>');
//Subtract(IncrementValue,PrecesionValue)
ButtonSubtract.setAttribute("onclick", "Subtract(1,1)");

var TextOutput = document.getElementById('<%=JSNumeric_Control.FindControl("Text_Output").ClientID%>');
alert('<%=JSNumeric_Control.FindControl("Text_Output").ClientID%>');
TextOutput.setAttribute("onkeyup", "check()");
TextOutput.value = 0;
}

If I add another user control, it will be initialized with the same settings even if I modify the ID for that specific user control. I aim for each user control to have its unique client ID so they can operate independently from each other?

Answer №1

   //Function to add values while handling special characters in the control ID.
   function Add(incValue, percValue,controlID) {
    //Replacing $ sign with _ character in the control ID name.
    var outputValue = document.getElementById(controlID.name.replace(/\$/g, '_')).value;
    var incrementValue = incValue;
    var precisionValue = percValue;

    if (outputValue.indexOf(".") > 0) {
        var total = (parseFloat(outputValue) + parseFloat(incrementValue));
        document.getElementById(controlID.name.replace(/\$/g, '_')).value = parseFloat(total).toFixed(parseInt(precisionValue)).toString();
    }
    else {
        if (percValue == 0) {
            document.getElementById(controlID.name.replace(/\$/g, '_')).value = parseInt((parseFloat(outputValue) + parseFloat(incrementValue)).toString());
        }
        else {
            var total = (parseFloat(outputValue) + parseFloat(incrementValue));
            document.getElementById(controlID.name.replace(/\$/g, '_')).value = parseFloat(total).toFixed(parseInt(precisionValue)).toString();
        }
    }
}

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

Invoking native code with a struct that exceeds the expected length in P/Invoke

Suppose I have a native code that is expecting a structure with two fields: [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern int my_method(ref MyStruct myStruct); // This is the structure that the native code exp ...

Steps for displaying a bootstrap modal in alignment with the triggering button's position

Recently diving into the world of bootstrap and AngularJs has been quite the learning experience for me. One challenge I encountered was trying to implement a bootstrap modal dialog box to show additional details within a table column. My goal was to hav ...

How to convert the string "yyyy-MM-dd hh:mm:ss 'UTC'" into a DateTime object in C#

Looking for a solution to convert a string like: "2022-04-17 14:46:31 UTC" Encountering an error while attempting to convert it to date time: The provided input '2022-04-17 14:46:31 UTC' is not recognized as a valid DateTime. An unre ...

Displaying live IP CAMERA feed using three.js

I am currently facing a challenge in rendering a video stream from an IP Camera to a three.js texture. I have attempted the following code snippet without success: .... var video = document.createElement('video'); video.crossOrigin="anonymous" ...

Creating multiple instances of an object

When using Javascript, I am trying to create an object in the following way: var testObject = { value: "this is my initial value", setup: function() { value: "foo" } }; Now, my goal is to instantiate this object and have different val ...

Direct your attention towards the bootstrap dropdown feature

I have encountered an issue with using a bootstrap dropdown. I need to focus on the dropdown in order to navigate through its options using the keyboard. However, my current attempt at achieving this using jQuery does not seem to be working when I use $(&a ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

The Bootstrap modal popup fails to appear when utilizing the fade animation effect

I incorporated Bootstrap's JavaScript modal plugin into my application to introduce dialog boxes. While I am able to use it successfully, I encountered an issue when attempting to implement a fade animation when opening or closing a modal dialog. Fol ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Error message: Vue warning - The prop "disabled" must be a boolean type, but a function was provided instead

I have this code snippet that I am currently using <v-list-item> <v-btn @click="onDownloadFile(document)" :disabled=getFileExtention >Download as pdf</v-btn > < ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

Defeat a JavaScript function or turn it into a Singleton Function

Is there a method to stop a running JavaScript function? Or is there a way to make sure that only one instance of the function runs at a time and any previous instances are removed upon restart? For example, if I call: _.defer(heavyDutyPaint); //How ca ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

Analyzing a CSV file and executing asynchronous operations on specific columns with the help of ajax requests

I possess a CSV file that contains placement links and target links formatted as follows: CSV Example [placement url],[target url] [placement url],[target url] [placement url],[target url] My objective is to parse the CSV file line by line using JavaScri ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Upon clicking a button, initiate an Ajax call to retrieve a value from the code behind (aspx.cs) and display it in an input field on the same page

I am a beginner in the world of AJAX and encountering a problem. I need to initiate an AJAX call when a button is clicked. The goal is to send the value of an input field to the code behind page, aspx.cs, and then display the response from that same input ...

construct a table utilizing JSON information

If I have data returned from an ajax call that needs to be processed, a table like the following needs to be created: ID NAME Object Type ============================================== 1 SWT-F1-S32-RTR-1 Network Switch 2 ...