Calculating the number of characters in each textarea by iterating through them with a

I am currently working on a project where I need to implement a character count feature for each field in my form. Below is a snippet of code from my C# file:

List<Document> record= _repository.Document.GetChecklist(entity.checklist, Convert.ToInt32(entity.ref)).ToList();

if (record.Count() > 0)
        {
            int i = 0;

            foreach (var r in record)
            {   
                _html.Append("<tr>");
                _html.Append("<td style=\"padding-left:20px\" class=\"td-control\">
                              <textarea cols=\"50\" rows=\"5\" maxlength=\"1000\" id=\"desc" + i + "\">" + (String.IsNullOrEmpty(r.desc) ? "" : r.desc.ToString().Trim()) + "</textarea>
                              <div id=\"char-count\">
                              <span id=\"current\">0</span><span>/ 1000</span></div></td>"
                _html.Append("</tr>");
                i++;

            }
        }    

In the CSS section, I have tried styling the character count display as follows:

#char-count
    {
        float: right;
        padding: 0.1rem 0 0 0;
        font-size: 0.875rem;
    }

However, when it comes to implementing the character count functionality using jQuery, I seem to be facing some challenges. Here is the jQuery code snippet that I have attempted:

        $("#desc").keyup(function () {
            $("#desc").each(function () {

                var characterCount = $(this).val().length,
                    current = $('#current');

                current.text(characterCount);

            });

        });

I apologize if my explanation is unclear. As a beginner in coding and English not being my first language, I may struggle with technical terms.

Answer №1

Having a

<textarea id="desc">
element with an ID is fine, but ensure that you are not creating multiple instances of it in a loop within your C# code. In HTML, an ID must be unique and can only exist once throughout the document.

If you require multiple textareas, consider using a class instead:

<textarea class="desc">
. This way, you can target all instances using the CSS selector .desc.

To handle multiple textareas and character counts while maintaining their relationship, it's advisable to add a class to a parent wrapping element. You can then easily access the inner elements as needed.

//Iterate through each wrapper element
$(".description-wrapper").each(function() {
  //select the necessary elements inside this wrapper
  const textEl = $(this).find('.desc');
  const countEl = $(this).find('.current-count');
  
  //Calculate character count on keyup event
  textEl.keyup(function () {
    countEl.text(this.value.length);
  });

  //Manually trigger the event on page load for initial count
  textEl.keyup();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="description-wrapper">
      <textarea class="desc">hello world</textarea>
      <p>Char count: <span class="current-count">0</span>/1000</p>
    </td>
  <tr>
    <tr>
    <td class="description-wrapper">
      <textarea class="desc"></textarea>
      <p>Char count: <span class="current-count">0</span>/1000</p>
    </td>
  <tr>
    <tr>
    <td class="description-wrapper">
      <textarea class="desc">foo</textarea>
      <p>Char count: <span class="current-count">0</span>/1000</p>
    </td>
  <tr>
</table>

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

Place the collapsible button on the right side of the navigation bar

Looking to position the collapsible button to the right of the navbar in Bootstrap v4, I attempted wrapping the button in: <div class='nav navbar-nav navbar-right'> I also tried adding the float-xs-right class without any luck. A sample ...

extract specific data from a JSON object

Given the JSON data below, how can I retrieve the address: '172.16.2.18'? I am specifically looking to extract 172.16.2.18 from the provided JSON data. Is there a way to achieve this? { 'Local Area Connection': [{ address: ...

Capture and transform every alert into a notification

I have implemented Gritter for notifications across my website and am curious if there is an easy method to intercept all alert() messages triggered by scripts using jQuery, and then display the contents of the alert in a Gritter notification. Is there a ...

Are you considering transitioning from ASP.Net Web Forms to ASP.Net MVC?

If the answer is affirmative, please specify when you plan to begin the migration process and provide an estimate of how long you believe it will take to migrate your current projects, if applicable. ...

The use of the overflow:hidden property in a div element continues to result in

This website features smooth scrolling with AJAX functionality. The design includes two divs - one is double the width of the browser window, while the other matches the width exactly. The container div has overflow:hidden to eliminate any scroll bars. De ...

Utilizing CodeIgniter for Efficient AJAX Posting

I'm struggling to submit a post using the ajax post method. It appears that the request is being posted without any error messages, but the model doesn't seem to respond and insert the row into the database. While I'm not well versed in jQu ...

Combining a standard JSS class with Material-UI's class overrides using the classnames library

I am exploring the method of assigning multiple classes to an element in React by utilizing the classnames package from JedWatson, along with Material-UI's "overriding with classes" technique. For reference, you can see an instance in MUI's docu ...

Utilizing CSS/HTML to optimize code for mobile applications

Looking for some help with implementing the Upcoming Events part from this code snippet: https://codepen.io/AbhijithHebbarK/pen/boKWKE .events-details-list{ opacity:0; transition: all 0.3s ease-in-out; position: absolute; left: 0; rig ...

What is the best way to prevent certain search terms from appearing in search results on my website's search form

Is there a way to prevent certain search terms from showing up in my search box? For example, how can I block the search query for "dog"? <form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech"> <input type="t ...

I am looking to dynamically insert a text field into an HTML form using jQuery or JavaScript when a specific button is clicked

This is my code snippet: <div class="rButtons"> <input type="radio" name="numbers" value="10" />10 <input type="radio" name="numbers" value="20" />20 <input type="radio" name="numbers" value="other" />other </div> ...

What is the best way to load specific CSS in an rhtml file?

In the world of website development, we often find several pages that are generated from the same layout.rhtml file. Along with a global css file, each page may also have its own unique css file - such as page1.css for page1.rhtml and page2.css for page2.r ...

Trigger an "onMouseMove" event when the "pointer-events-none" css property is applied to fire

Currently, I am dealing with a React Component that contains an absolutely positioned div overlaying other content within my application. This particular div is utilized to trigger react's onMouseMove event. My objective is to apply the CSS value poi ...

Selecting radio button does not update corresponding label

I am having an issue with setting a radio button as checked. In the example snippet, it works perfectly fine but on my localhost, it is not working. Even though the input gets checked, the label does not change. Surprisingly, if I set another radio button ...

Continuously maintaining the .aspxauth membership cookie

After transferring a website to a new hosting provider, I encountered an issue with the forms authentication. Prior to the migration, users could stay logged in across sessions without any problems. However, post-migration, users are being unexpectedly lo ...

Issue with Bootstrap Dropdown menu: No dropdown list is being displayed

I am having an issue with the code snippet extracted from the Bootstrap website. Everything seems to be working fine, but when I click on "See Product", nothing shows up. <!DOCTYPE html> <html> <head> <title>Omicron.com&l ...

Retrieve Django API information from a dynamic URL utilizing Ajax-Jquery [No need for REST Framework]

For my server-side application built with Django, I am required to display articles based on the URL, which includes the year, month, and user_id of the articles. For example, blog/1/2022/8 should display all articles from August. In my client-side applic ...

AngularJS - Showing only items belonging to the same team

Currently, I am attempting to filter out all objects that belong to the same team. Each object is structured as follows: {"first_name":"Bob","last_name":"Sagat","username":"bobsagat", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Adding text can only be done to the initial list item

I have a menu structured like this: <ul class="nav"> <li class="dropdown" id="123"> <ul class="nav123"> <li id="widget-products"> <ul class="123">// content populate ...

Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed. Below is a snippet of ...

Experiencing excessive memory usage when attempting to load a large JSON file in Firefox

We are in the process of developing a client-based application using HTML5 and indexedDB on Firefox 28. When large amounts of data are loaded to Firefox for the first time using AJAX requests in JSON format, each JSON response is approximately 2MB (gzipped ...