I have a "characters remaining" counter for my Shopify store that shows how many characters a customer has left to enter in a text box. It works perfectly when I have one text box on the page, but if there are two or more, the countdown text does not show at all. Any ideas on how to get this to run for multiple times on the same page?
$(document).ready(function() {
var text_max = $('#line_item_text').attr('maxlength');
$('#personalization_feedback').html(text_max + ' characters remaining ');
$('#line_item_text').keyup(function() {
var text_length = $('#line_item_text').val().length;
var text_remaining = text_max - text_length;
$('#personalization_feedback').html(text_remaining + ' characters remaining ');
});
});
Instead of using id on HTML elements, you need to use classes because the same id is not allowed more than once into an HTML document, if you add it then it does not work.
So use classes and loop the code over each element like you adding using id.
$(document).ready(function() {
$('.line_item_text').each(function(idex,ele){
var text_max = $(ele).attr('maxlength');
$(ele).next().html(text_max + ' characters remaining ');
$(ele).keyup(function() {
var text_length = $(ele).val().length;
var text_remaining = text_max - text_length;
$(ele).next().html(text_remaining + ' characters remaining ');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="50" class="line_item_text"></textarea>
<div id="txt1"></div>
<textarea maxlength="50" class="line_item_text"></textarea>
<div id="txt2"></div>