Getting jQuery selector to recognize newly-added DOM elements

0 votes

I've searched the jQuery docs and here and can't find an answer to my exact problem...

With a DRY spirit, I want to use javascript to add a character object countdown helper to any textarea element with maxlength and aria-describedby attributes.

Obviously I also need to use javascript to monitor keyup events to update the counter. I'm using jQuery 3.6.0. However, I can't seem to get the countdown method to recognize the newly-added "helper" div element. Here's what I have so far:

$(document).ready(function () {

    // "characters remaining" countdown
    function textCounter(field) {
        var charLimit = field.attr("maxlength");
        console.log("charLimit=" + charLimit);
        // hack to *double-count* '\r\n' (client/DB discrepency)
        var numLines = (field.val().match(/\n/g) || []).length;
        var charLength = field.val().length + numLines;
        console.log("charLength=" + charLength);
        var charDiff = charLimit - charLength;
        console.log("charDiff=" + charDiff);
        if (charLength > charLimit - numLines)
            field.val(field.val().substring(0, charLimit - numLines));
        var count = $("#" + field.attr("aria-describedby") + " .count");
        console.log(count.html());
        count.html(Math.max(0, charDiff));
    }

    // add countdown helper div
    $("textarea[maxlength]").each(function (e) {
        var helpID = "#" + $(this).attr("aria-describedby");
        var helpDiv = $('<div id="' + helpID + '"><span class="count"></span> characters left.</div>')
        $(this).after(helpDiv);
        textCounter($(this));
    })

    // update counter on keyup events
    $("textarea[maxlength]").keyup(function () { textCounter($(this)); })

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="2000" aria-describedby="content-help" id="content" name="content"></textarea>

 Run code snippet

Expand snippet

I can confirm that:

  1. The helper div element is getting added
  2. Via the console.log statements, the textCounter() method is getting called, but the count object resolves to undefined (even though it is clearly there), and
  3. If the element is hardcoded in HTML (i.e., not dynamically added) the counter works as expected.

Other searches suggest that .delegate() or .on() are part of the answer, but everything I've tried has the exact same behavior as above. :( Every other Q/A I've come across is, for example, binding a click/hover event to the newly-added element, but here it's the textarea that needs monitoring (not the new helper element, although it will be updated), if that makes sense...

Note that I want the solution to work on pages that have multiple textareas, each with potentially different maxlength attributes.

Any thoughts how to accomplish this?

Aug 18, 2022 in Web Development by gaurav
• 23,260 points
1,494 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Web Development

0 votes
1 answer

How to change an element's title attribute using jQuery

You can change the title attribute with ...READ MORE

answered Jun 30, 2022 in Web Development by rajatha
• 7,640 points
3,569 views
0 votes
0 answers

jQuery exclude elements with certain class in selector

I want to setup a click event ...READ MORE

Jul 20, 2022 in Web Development by gaurav
• 23,260 points
947 views
0 votes
0 answers

Getting a jQuery selector for an element

In psuedo code, this is what I ...READ MORE

Aug 11, 2022 in Web Development by gaurav
• 23,260 points
420 views
0 votes
0 answers

Getting the Text of a Check Box and Text Area To Display using jQuery

What I am trying to do is ...READ MORE

Aug 18, 2022 in Web Development by gaurav
• 23,260 points
1,489 views
0 votes
0 answers

Getting elements that exceed the maxium value. JAVASCRIPT/JQUERY

greetings, I'm new with java script so bear ...READ MORE

Aug 24, 2022 in Web Development by gaurav
• 23,260 points
202 views
0 votes
0 answers

Uncaught TypeError: Cannot read property 'top' of undefined

I have two different kinds of sticky ...READ MORE

May 11, 2022 in Java-Script by Kichu
• 19,050 points
2,669 views
0 votes
1 answer

What is jQuery?

Hey, jQuery is a fast and concise JavaScript ...READ MORE

answered Feb 14, 2020 in JQuery by kartik
• 37,510 points
973 views
0 votes
1 answer

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Hello, Use the following script tag in your ...READ MORE

answered Apr 28, 2020 in JQuery by Niroj
• 82,880 points
14,125 views
0 votes
1 answer

Uncaught Error: Bootstrap's JavaScript requires jQuery

Hello @kartik, You have provided wrong order for ...READ MORE

answered Apr 28, 2020 in JQuery by Niroj
• 82,880 points
22,372 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP