alicia233 alicia233 - 3 months ago 12
Javascript Question

character counter not functioning when echoed repeatedly in a table

I'm trying to use the javascript character counter below in multiple textareas within my table. The problem is the counter only functions in the first row of my table. Subsequent rows with textareas echo "250 characters remaining", but do not function as intended. I'm not sure how to assign each character counter with a unique id so it functions in all textareas. Any help would be appreciated.

PHP:

echo "</td><td>";
echo '<form action="peerflagreview.php?foorbar=' . $foobar . '" method="post" id="FlagPeerReview">
<A NAME="#peer' . $foobar . '"> (<a href="#peer' . $foobar . '" class="show_hide2">Report</a>)
<textarea class="PeerFlag" value="" name="PeerFlag" id="PeerFlag2"></textarea>
<input type="hidden" value="Post" name="submit" />
<span id="PeerFlag2Span">250 characters remaining</span>
<input type="submit" value="Submit"></form>';
echo "</td></tr>";


JAVASCRIPT:

<script type="text/javascript">
$("#PeerFlag2").on('change keydown paste input', function(){
updateCounter('#PeerFlag2');
});
function updateCounter(theTextAreaID) {
// 250 is the max message length
var remaining = 250 - jQuery(theTextAreaID).val().length;
jQuery(theTextAreaID + 'Span').text(remaining + ' characters remaining.');
}

$('textarea').on('keydown', function(event) {
if (event.keyCode == 13)
if (!event.shiftKey) $('#PeerFlag').submit();
});

</script>

Answer

This is a very simple demo so I don't see of much explain needed other than this will target the next span of the textarea in use. I see you already have jQuery so this demo will also use jQuery.

$(document).ready(function () {
$(".UserInput").on('input', function(){
      $(this).next("span").html(250-this.value.length+" characters remaining ");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="UserInput"></textarea><span>250 characters remaining</span><br/>
<textarea class="UserInput"></textarea><span>250 characters remaining</span><br/>
<textarea class="UserInput"></textarea><span>250 characters remaining</span><br/>
<textarea class="UserInput"></textarea><span>250 characters remaining</span><br/>

If you have any questions please leave a comment below and I will get back to you as soon as possible.

I hope this help. Happy coding!