Sending ASP.NET Components to JavaScript Functions

I've set up a text box and label in the following way:

<asp:TextBox ID="MyTextBox" runat="server"/>
<asp:Label   ID="MyLabel"   runat="server"/>

Additionally, I've created a JavaScript function like this:

function checkLength(myTextBox, myLabel)
{
    myLabel.innerHTML = myTextBox.value.length + '/' + myTextBox.maxLength;
}

Lastly, in the code-behind, I've implemented the following:

TextBox1.Attributes.Add("OnKeyUp", "checkLength(MyTextBox, MyLabel);");

When checkLength() is triggered, nothing seems to happen. It appears I may be passing MyTextBox and MyLabel incorrectly. How should I approach this?

Answer №1

Utilize the ClientID attribute. This is especially useful when incorporating MasterPages, as it alters the IDs of controls.

However, in this particular scenario, it seems like simply adding quotes around the IDs when passing them as parameters should suffice.

TextBox1.Attributes.Add("OnKeyUp", "characterLimit('" + MyTextBox.ClientID + "','" +  MyLabel.ClientID + "');");

As recommended in the comments, you may want to make a slight adjustment to your Javascript code:

function characterLimit(myTextBox, myLabel)
{
    document.getElementById(myLabel).innerHTML = myTextBox.value.length + '/' + document.getElementById(myTextBox).maxLength;
}

Also, if you haven't already, consider experimenting with jQuery for more functionality.

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

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

Display each div one at a time

I am working on a script that should reveal my divs step by step. However, the current code only shows all the divs at once when clicked. How can I modify it to detect each individual div and unveil them one by one? For example, on the 1st click => expa ...

What is the best way to eliminate all padding from a bootstrap toast notification?

I'm attempting to display a bootstrap alert message as an overlay toast (so it automatically disappears and appears above other elements). Issue: I am encountering a gap at the bottom of the toast and struggling to remove it: https://jsfiddle.net/der ...

Generating DOM elements at specific intervals using Jquery

I am looking to dynamically create 1 div container every x seconds, and repeat this process n times. To achieve this, I have started with the following code: $(document).ready(function() { for (var i = 0; i < 5; i++) { createEle(i); } }); f ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

Experiencing difficulty with updating a table in Linq to Entities using the update statement, however, the table is not being updated

My form contains buttons for adding, editing, and saving, as well as a datagridview. I use this form to update existing product entities and add new ones, then display the updated data in the datagridview. When I click the edit button, the save button ap ...

What is the best way for me to automatically square a number by simply clicking a button?

How do I create a functionality that multiplies a number by itself when a specific button is clicked? I want this operation to only occur when the equals button is pressed. I have been attempting to set this up for over an hour without success. My current ...

send JSON data to a Spring MVC endpoint

Here is the controller signature I have tried using @RequestBody: @RequestMapping(value = "/Lame", method = RequestMethod.POST) public @ResponseBody boolean getLame(@RequestParam String strToMatchA, @RequestParam String strToMatchB) {} This is the json I ...

Increase the Value of a Model Using the Power of Ajax and Razor

While iterating through a collection in my model using Razor to render it, one scenario could be: @foreach(var item in myCollection) { <span id='<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b425f4e46066b425f4e46 ...

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

The jQuery Ajax script fails to send data to the webservice function

Having trouble passing values from my ajax code to my webservice method. I believe I may be doing something wrong. Any guidance would be appreciated. This is the code in my .aspx file: $(function () { $.ajax({ type: "POS ...

Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation: //this works angular.module("myApp", []); angular.module('myApp', ['myApp.myD', 'myApp.myD1&a ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Tips for presenting JSON date in JavaScript using Google Chart

I am in urgent need of assistance with this issue. I am trying to display the date from PHP JSON data retrieved from my database in a Google Chart using JavaScript. Below is the PHP code snippet: $data_points = array(); while($row = mysqli_fetch_array($r ...

Discover the magic of retrieving element background images on click using jQuery

I am attempting to extract the value for style, as well as the values inside this tag for background-image. Here is the script I have tried: function getImageUrl(id){ var imageUrl = jQuery("."+id+". cycle-slide").attr("src"); alert('' + ima ...

Showing JSON information fetched from an AJAX request within an HTML page

I've been working on a project and I'm almost there with everything figured out. My main challenge now is to display an array of items on a web page after making an ajax call. Below is the code snippet I currently have: JQuery Code: var su ...

Is there any way to extract the source files from a compiled Electron application?

Is there a way to extract the contents of a .app Application developed using Electron for Mac OS? I'm eager to explore the underlying source files, but I'm not familiar with the procedure to access them. Any assistance would be greatly appreciate ...

Loop through each object in an array and verify if the value matches a specific criteria in Javascript

Explore the common issues related to object iteration and queries outlined below. Presented here is a list of objects (used for managing a connection form): const connectionData = { mail: { value: false, isRequired: true }, password: { v ...

Create a dynamic HTML table in React by leveraging arrays

I am working with two arrays: headings=['title1','title2'] data=[['A','B'],['C','D']] How can I efficiently convert this data into an HTML table that is scalable? title1 title2 A B ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...