Sam Khan Sam Khan - 2 months ago 6
jQuery Question

Jquery characters exceeding characters, show positive value then?

Currently whats happening in this function is that when the characters exceed over 2000, it starts showing -x amount of characters remaining i.e. -1 characters remaining. I want it to i.e. when the characters exceed over 2000 I want it to show 1 characters over the limit etc...



$(document).ready(function() {
var text_max = 2000;
$('#textarea_feedback').html(text_max + ' character available.');

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

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="YourMessage"></textarea><br/> <span id="textarea_feedback"></span>




Answer

Here is a version that will get the absolute value of the remaining. If the remaining are above 0 it shows one text, below another

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

  $('#YourMessage').keyup(function() {
    var text_length = $('#YourMessage').val().length;
    var text_remaining = text_max - text_length;
    var characters = " character"+(Math.abs(text_remaining)==1?"":"s");
    $('#textarea_feedback').html(Math.abs(text_remaining) + characters + (text_remaining > 0? ' remaining.':' over the limit.'));
    $('#textarea_feedback').toggleClass("red",text_remaining<0).toggleClass("green",text_remaining>=0)
  });
});
.red { color:red; }
.green { color:green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="YourMessage"></textarea><br/> <span class="green" id="textarea_feedback"></span>

Comments