Setting character limits within textareas based on CSS classes in a dynamic manner

I'm looking to develop a JavaScript function that can set text limits for multiple textareas at once using a class, allowing for flexibility in case specific textareas need to be exempt. However, I'm facing issues with my debuggers - Visual Studio isn't providing IntelliSense and JSFiddle isn't showing any errors. I'm struggling to figure out how to troubleshoot this situation effectively. Jquery is optional for me; I currently have a version of the code that only uses CSS ids.

$('.txtFeedback').html("characters remaining");
try {
  $(document).ready(function() {
    var textareas = document.getElementsByClassName("txtLimit");
    var feedbacks = document.getElementsByClassName("txtFeedback");
    var n = 0;
    for (var i = 0; i < textareas.length; i++) {
      var thisElem = textareas[i];
      var countX = textareas[i].style.marginLeft;
      $("#" + thisElem.id).keyup(function() {
        var text_length = $("#" + thisElem.id).val().length; //char count
        var text_remaining = $("#" + thisElem.id).maxLength - text_length;
        if (countX < thisElem.maxLength) {
          $("#" + feedbacks[n].id).css({
            marginLeft: '+=50pt'
          });
          countX += 50;
        }
        $("#" + feedbacks[n].id).html(text_length + '/' + text_max);
      });
      n++;
    }
  });
} catch (err) {
  document.getElementById("errors").innerHTML = err.message;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" class="txtLimit" rows="8" cols="30" maxlength="99" style="z-index:1;"></textarea>
<div id="textarea_feedback" class="txtFeedback" style="z-index:2; margin-top:-18pt; margin-left:50pt"></div>
<div id="errors" width=100 height=3 00/>

Answer №1

To properly retrieve the id of a feedback element, you must first store it in a variable. I have made the necessary adjustments to your code snippet to address this issue. Additionally, I noticed that the variable text_max was not defined, so I have set its value arbitrarily to 300.

Just a heads up, you can utilize the developer console (press F12) in JSFiddle to catch any errors.

UPDATE: After considering the feedback provided, I have modified text_max to be thisElem.maxLength.

$('.txtFeedback').html("characters remaining");
try {
  $(document).ready(function() {
    var textareas = document.getElementsByClassName("txtLimit");
    var feedbacks = document.getElementsByClassName("txtFeedback");
    for (var i = 0; i < textareas.length; i++) {
      var thisElem = textareas[i];
      var text_max = thisElem.maxLength;
      var feedback = feedbacks[i];
      var countX = textareas[i].style.marginLeft;

      $("#" + thisElem.id).keyup(function() {
        var text_length = $("#" + thisElem.id).val().length; //char count
        var text_remaining = $("#" + thisElem.id).maxLength - text_length;
        if (countX < thisElem.maxLength) {
          $("#" + feedback.id).css({
            marginLeft: '+=50pt'
          });
          countX += 50;
        }
        $("#" + feedback.id).html(text_length + '/' + text_max);
      });
    }
  });
} catch (err) {
  document.getElementById("errors").innerHTML = err.message;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" class="txtLimit" rows="8" cols="30" maxlength="99" style="z-index:1;"></textarea>
<div id="textarea_feedback" class="txtFeedback" style="z-index:2; margin-top:-18pt; margin-left:50pt"></div>
<div id="errors" width=100 height=3 00/>

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

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

Malfunctioning Line in Apple Safari Causing ReactJS Issues

I am encountering an issue with my <div className={`${classes.center} ${classes.or}`}>OR</div>. It appears that this problem is specific to Apple Safari only. The alignment on the right side seems to be broken, although it works fine on Google ...

What exactly entails static site generation?

I have been exploring the concept of static site generation (SSG). The interesting question that arises is how SSG can fetch data at build time. In my latest application, I implemented an event handler to retrieve data based on a user's search keyword ...

Is the p tag not becoming absolute from the bottom even when set to position: absolute?

My p tag in the section properties of div class="sf sf_2 won't align to 0 px from the bottom of the div. It seems to move 0px from the top, right, and left but not bottom. I've tried changing its position property and where it's nested, but ...

Storing information in a table before having an assigned ID

Currently, I am developing a CMS using Codeigniter which consists of standard fields like title and post content, similar to Wordpress. On my page, there is an image uploader that utilizes ajax to save images to a MySQL table with basic fields including i ...

What is the process of transferring information from a form to mongodb?

I have created a nodejs project with the following structure: https://i.stack.imgur.com/JiMmd.png api.js contains: const express = require('express'); const router = express.Router(); const add = require('../model/myModel'); router.g ...

Optimizing CSS for printing by eliminating unnecessary white space with media queries

Appreciate your assistance! I'm currently working on a solution to print a specific div using CSS Media queries. When the user clicks on print, I want to hide all other elements except for the body div they chose. However, I'm facing an issue whe ...

Backstretch malfunctioning

Looking to enhance my webpage with a backstretch image slideshow effect using the body background, but encountering issues. The code I have included before the </head> tag is: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

After each alert triggers a page refresh, it should not automatically refresh. To prevent the refresh, I implemented a preventDefault function that works seamlessly in Chrome but not

My code is experiencing an issue where event.preventDefault() works in Chrome, but not in Firefox. I have tried both methods and searched for solutions, but nothing seems to be working. If needed, I can post all of my code if the error cannot be found. fu ...

error message remains visible even after correct input is entered

I am new to React and attempting to create a multi-step form using Reactjs and Material-ui. The form validation and submit buttons are working perfectly fine. However, I have encountered an issue with the code where if a field is empty and I try to proceed ...

The requested TYPO3 eID for ajax functionality could not be found and returned a

I am using TYPO3 version 7.6.18 and attempting to set up ajax requests on the front end. I need the ajax request to call a specific plugin controller and action. I have tried different AjaxDispatchers, but now I am encountering a 404 error stating "eID not ...

Vue component does not display FabricJS image

Currently, I am facing an issue where I want to manipulate images on a canvas using FabricJS inside a VueJS app. In the view component, there is a prop called background which I pass in and then use fabric.Image.fromURL() to load it onto the canvas. Howeve ...

The left margin is malfunctioning

As a newcomer to css, I am struggling with adding margin-left to my paragraph and <h2>, and it's not taking effect. I have a 700px div and I want to add a 10px margin-left to both <p> and <h2> in relation to the image. Despite my e ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

Designing a Vue 3 JS component that showcases a collection of attributes for a movie catalog

I am aiming to utilize the movie_properties in order to store various details such as movie id, name, genre, comingSoon status, availability, thumbnail, and preview. It's important to note that I am working with an API call that contains all this inf ...

Currently focusing on improving the responsiveness of the navigation bar and grid layout

I'm facing a new challenge I can't seem to crack: Despite setting my grid boxes to be responsive with 1fr column and (6, fr) row, they are displaying poorly on mobile devices. Additionally, my navbar remains fullwidth and mobile-like even when i ...

Exploring the seamless integration of Material UI slider with chart js

Looking for guidance on syncing Material UI slider with chart js? I'm working on a line chart and hoping to have the x-axis value highlighted with tooltip as I slide the Material UI slider. ...

Executing a javascript function from PHP when a form is submitted: a comprehensive guide

I am looking to trigger a javascript function from PHP when the form is submitted. This function will have access to PHP variables and will use AJAX to send them to a PHP script on another website. The code below serves as an example: <?php .... ..... ...