Reputation: 1123
I am using a jQuery function to generate a character countdown below a textarea field for our site's users (X Characters Remaining). My form is several pages long (somewhat like a wizard) and users typically go forward and back throughout the pages. When I go back a step and reload a page that was already completed, my character countdown displays '3000 Characters Remaining'. It's not counting the number of characters on page load. If a user goes back through the forms, I would like the function to be triggered and count the number of characters that were already entered into the textarea field.
# The jQuery Function
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var limit = $(this).data("limit");
var remainingChars = limit - $(this).val().length;
if (remainingChars <= 0) {
$(this).val($(this).val().substring(0, limit));
}
$(this).closest('div').find(".countdown").text(remainingChars<=0?0:remainingChars);
});
});
# HTML
<textarea data-limit="3000"></textarea>
<span class="countdown">3000</span> Characters Remaining
Upvotes: 2
Views: 1383
Reputation: 1
<textarea id="comments" cols="1000" rows="3"></textarea>
Characters Remaining : <span id="countdown">200</span>
<script type="text/javascript">
$(document).ready(function () {
$('#comments').on("load propertychange keyup input paste",
function () {
var limit = 200;
var remainingChars = limit - $(this).val().length;
if (remainingChars <= 0) {
$(this).val($(this).val().substring(0, limit));
}
$("#countdown").text(remainingChars<=0?0:remainingChars);
});
$('#comments').trigger('load');
});
</script>
Upvotes: 0
Reputation: 6689
In your document ready function just add:
$('.countdown').text(
function () {
var limit = $(this).data("limit");
var remainingChars = limit - $(this).val().length;
if (remainingChars <= 0) {
$(this).val($(this).val().substring(0, limit));
}
});
Since you are repeating the inside function you can consider to take it out of each of the jquery statement and refer to it inside
Upvotes: 0
Reputation: 5187
I think you are very close. I have made minor changes in your code and the working solution is given below,
$(document).ready(function () {
$('textarea').val('some text');
$('textarea').on("load propertychange keyup input paste",
function () {
var limit = $(this).data("limit");
var remainingChars = limit - $(this).val().length;
if (remainingChars <= 0) {
$(this).val($(this).val().substring(0, limit));
}
$(".countdown").text(remainingChars<=0?0:remainingChars);
});
$('textarea').trigger('load');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea data-limit="3000"></textarea>
<span class="countdown">3000</span> Characters Remaining
Upvotes: 4