I have a button that creates a dynamic textarea
field with a unique id
. Each time a new element is created, I want jQuery to trigger on those dynamic textarea fields.
I tried the .on('click')
method and it doesn't run the jQuery on the dynamic element unless the button that generates them is pushed twice. So that won't work. Secondly, when I create a second dynamic textarea field, it doesn't work at all, even if I click the button twice.
jQuery('button').on('click', function() {
var dynamicElement = jQuery('.parentclass').find('textarea').attr('id');
//countChar is part of a function not displayed here (works fine).
countChar(jQuery('#'+dynamicElement).get(0));
//This code below never seems to apply itself to any dynamic textarea fields except for
//the first one. It needs to apply itself to all of them and trigger each time a new
//dynamic textarea field is created.
jQuery('#'+dynamicElement).keyup(function() {
countChar(this);
})
});
How would I go about making this work?
Thank you.
EDIT
Here is the function countChar (it adds a character counter and limits the characters too).
Function
function countChar(val) {
var allowed_length = 700; // character count limit here
var len = val.value.length;
if (len >= allowed_length) {
val.value = val.value.substring(0, allowed_length);
jQuery(".chars[data-textarea="+val.id+"]").text(0);
} else {
jQuery(".chars[data-textarea="+val.id+"]").text(allowed_length - len);
}
}
HTML
<tr class="parentclass">
<td class="label">
<label>
Custom Title
</label>
<span class="field-instructions">
Please enter the content of this field.
Remaining: <span class="chars" data-textarea="dynamic-textarea-1"></span>
</span>
</td>
<td>
<div class="inner">
<textarea rows="4" id="dynamic-textarea-1" class="textarea"></textarea>
</div>
</td>