Skip to content
Advertisement

Remaining characters if data exists Javascript

I have a web site where users create an account and that information is saved to a JSON. When the user hits “save” the page refreshes and that data is echoed in the field pulling from the JSON. The problem I am experiencing is in one text area I want to limit the amount of characters. The script works perfectly IF there is no data in that textarea. The problem, that I can’t figure out, is if there is data, because the user saved it, the countdown text is still 100 and the user can continue typing more information. What I want is when the page refreshes, the Javascript counts the JSON information pre-filled in that text area and counts. Basically once the user saves the data into the JSON and the page refreshes the Javascript counts whatever text is pre-populated. Hope this makes sense. Here are the codes I have.

The text area

<textarea spellcheck="false" id="textarea" maxlength="100" 
name="welcome" required><?php if (!empty($main_data->welcome)) 
{ echo urldecode($main_data->welcome); } ?></textarea>

The Javascript:

<script>   
$(document).ready(function() {
var text_max = 100;
$('#textarea_feedback').html(text_max + ' characters remaining');

$('#textarea').keyup(function() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});

</script>

Advertisement

Answer

You can trigger() the event after binding it on page load. The method will execute the event handler and thus the desired result will be achieved.

Execute all handlers and behaviors attached to the matched elements for the given event type.

$('#textarea').on(......).trigger('keyup'); //Notice here

$(document).ready(function() {
  var text_max = 100;
  $('#textarea_feedback').html(text_max + ' characters remaining');

  $('#textarea').on('keyup', function() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
  }).trigger('keyup'); //Notice here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea spellcheck="false" id="textarea" maxlength="100" name="welcome" required>PrefilledText</textarea>
<div id="textarea_feedback"></div>

However, I would recommend you to create a method. Then you can invoke it on page load and use it as event handler.

function setFeedback() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
}

//Set on page load
setFeedback();

//Bind event
$('#textarea').on('keyup', setFeedback);
Advertisement