javascript utilize function parameters to pass control names

Is there a way to pass control IDs from code behind to HTML without knowing the control names in advance due to dynamic generation? The regular method using

MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
won't work in this scenario.

How can I modify the following code to achieve the desired functionality:

            TextBox test = ((TextBox)e.Row.Cells[7].Controls[0]);
            test.ID = "TextBox1";
            TextBox test2 = ((TextBox)e.Row.Cells[8].Controls[0]);
            test2.ID = "TextBox2";
            test.Attributes.Add("onChange", "javascript:MyFunc(TextBox1, TextBox2);");

JS function:

function MyFunc(TextBox1,TextBox2) {
            MyTextBox = document.getElementById("TextBox1");
            MyTextBox2 = document.getElementById("TextBox2");

            var splitDate = MyTextBox.value.split('/');
            var date = new Date(splitDate[2], splitDate[1] - 1, splitDate[0]);

            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear() + 1;
            if (day < 10) {
                day = '0' + day;
            }
            if (month < 10) {
                month = '0' + month;
            }

            MyTextBox2.value = day + "/" + month + "/" + year;
        }

Answer №1

It's important to note that since the IDs are variables, you should avoid enclosing them in quotation marks.

let myTextBox = document.getElementById(TextBox1);
let myTextBox2 = document.getElementById(TextBox2);

Another thing to keep in mind is that you need to modify

test.Attributes.Add("onChange", "javascript:MyFunc('TextBox1', 'TextBox2');");

because both TextBox1 and TextBox2 must be passed as strings in this case.

Answer №2

Here is a way to achieve the desired functionality:

 TextBox textBoxOne = ((TextBox)e.Row.Cells[7].Controls[0]);
            textBoxOne.ID = "TextBox1";
            textBoxOne.Attributes.Add('class','TextBox1');
            TextBox textBoxTwo = ((TextBox)e.Row.Cells[8].Controls[0]);
            textBoxTwo.ID = "TextBox2";
            textBoxTwo.Attributes.Add('class','TextBox2');
            textBoxOne.Attributes.Add("onChange", "javascript:MyFunction(TextBox1, TextBox2);");

And in JavaScript:

function MyFunction(TextBox1, TextBox2) {
            var myTextBox = document.getElementByClass("TextBox1");
            var myTextBox2 = document.getElementByClass("TextBox2");

            var splitDate = myTextBox.value.split('/');
            var date = new Date(splitDate[2], splitDate[1] - 1, splitDate[0]);

            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear() + 1;
            if (day < 10) {
                day = '0' + day;
            }
            if (month < 10) {
                month = '0' + month;
            }

            myTextBox2.value = day + "/" + month + "/" + year;
        }

Answer №3

test.Attributes.Add("onChange", "javascript:MyFunc(" + TextBox1.ClientID + ", " + TextBox2.ClientID + ")");

Feel free to give this a try.

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

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

JavaScript Tutorial: Merging Two Arrays while Maintaining Original Index Positions

I have two arrays that I need to merge together. One array contains numbers, while the other array contains the corresponding titles for those numbers. This data was retrieved from a csv file, hence the current structure of the arrays. Array 1: dataResul ...

Is it possible for me to retrieve/load a <datalist> element from a different file?

I'm in the process of developing a Google Chrome extension that essentially consists of a dropdown menu and an input box with datalists. The user can change their selection in the dropdown menu, which will then switch the datalist being used by the in ...

Is it possible to pass parameters through a GET query to Vue.js?

When I apply a filter, the query in the API disappears. A PHP developer suggested that the request should be GET instead of POST. How can I pass parameters to the GET query? Here is an example of my POST request: export const filterDate = (options) => ...

What is the process for setting `name` and `inheritAttrs` within the `<script setup>` tag?

Options API: <script> import { defineComponent } from 'vue' export default defineComponent({ name: 'CustomName', // ...

Is it incorrect to append an array to a ul block using jQuery?

I am encountering an issue when trying to append an array to HTML. The array consists of HTML elements, starting with "li", then "img", and ending with "/li". When I try to append the array, it returns: <li></li> <img src="..."> Howeve ...

Updating a partial view in Asp.net and simultaneously downloading a file

I am facing a challenge with my website that has a list of downloads and a history of already downloaded files. Whenever I click on a file, I want it to start downloading and be added to the history list. The download functionality is working correctly wit ...

The three.js JSON model is rendering larger than expected on the screen

I'm currently working with three.js and I've successfully loaded a JSON file from clara.io into THREE.js. However, the 3D model is too large for my screen. Is there a way to reduce its size when loading it onto the screen? <!DOCTYPE html> ...

Tips for handling multi-line input in a textarea when the user presses the "enter/return" key

Trying to solve a coding issue: ... <textarea name="TextArea1" id="TextArea" style="height ; width" ></textarea> ... <script type="text/javascript"> var txt_element = document.getElementById("TextArea"); document.write (txt_element ...

Tips for properly passing a Vue3 Ref variable as a reference (plus the mystery of the "global" variable)

I created a custom Quasar/Vue3 component called TemperatureOutside.vue: <template> <div class='text-large-1 text-weight-bold'> {{ temperature }}° </div> </template> <script setup lang='ts'> import ...

Avoid cascading of the 'display' property in JavaScript styling to prevent inheritance

Is there a way in Javascript to toggle the visibility of a larger portion of HTML without affecting inner display properties with display: <value>? Despite setting an outer display property using Javascript, the inner display properties are also alt ...

Guide on displaying content in two different tabbable ID's when one tab is selected in a Rails 3.2 App using Twitter Bootstrap's Tabbable Tabs

My implementation using Twitter Bootstrap's bootstrap-tab.js includes: <ul class="tabnavcenter" id="myTab"> <li class="active"><a href="#home" data-toggle="tab">about</a></li> <li><a href="#tab2" data-togg ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

JavaScript - Struggles with developing a personalized AJAX function

I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response. The function in question is named ajaxPost(paramArray, target). It takes param ...

Encountering a 502 Bad Gateway error when trying to access a Dockerized ASP.NET Core Web API deployed on

Here is the content of my docker-compose.override.yml: version: '3.4' services: helen.api: environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=http://+:5000 ports: - "5001:443" - " ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...

What is the best way to design a navigation bar for a one-page application using Vue?

Currently, I am developing a Vuejs single-page application and I'm exploring ways to implement a navbar that can toggle the visibility of different sections within the app upon clicking. While I have successfully designed the navbar layout, I am encou ...

Selecting either "THREE.NearestFilter" or "THREE.LinearFilter" will result in the black plane

During my experimentation with the THREE.js library, I encountered a notification stating: THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. To address this issue, I made the ...

Guide to efficiently populating a self-referential Mongoose model

My goal is to populate data across multiple levels using the fields from an Article model: comments: [ { type: Schema.Types.ObjectId, ref: "Comment" } ] and also from ...

Utilize Selenium C# to locate and update information within a text file

I have a situation where I need to upload a text file in the UI, but this text file requires updating every time before the test is run. To achieve this functionality, I am looking to capture it within my Selenium C# script. The data format of the text fi ...