Paulo Henrique Queiroz
Paulo Henrique Queiroz

Reputation: 612

Remaning characters textarea problems

I am facing the following problem: I have to calculate the remaining characters in a textarea. It is a simple task and there's a lot of reference for doing such things. The piece of code I created to do this is bellow. Everything works fine an so, but, the QA team did this: they cut and pasted a piece of text of a txt document and they pasted till they reached the maximum of text allowed in my textarea. But what happens is that even when the max of characters is not reached the user cant type anymore.

And also if I erase some characters using the backspace I cant type anymore.

Let me be more specific. Let's say that the last word is "nerd" and the remaining characters is "47". The code doesn't allow me to write more and even if I use the backspace and have "ner" I cant type a single more letter!

The fiddle bellow has the scenario to check what I am saying. You can paste the text that is in the comment of the html section of my fiddle to state what I am talking about. Thanks in advance for any help.

http://jsfiddle.net/sLr8co1n/4/ GIF: http://gifmaker.cc/PlayGIFAnimation.php?folder=2015020423hlKs7Ki7knoQBCZAoSaQNN&file=output_rwGbzN.gif

$("#textAreaComplemento").bind("keyup change", function (e) {
   calculaCaracteresRestantes();
});
var text_max = 200;
function calculaCaracteresRestantes() {
 if ($('#textAreaComplemento').val() == undefined) {
    return false;
 }

var text_length = $('#textAreaComplemento').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining);

  return true;
 }

Upvotes: 2

Views: 68

Answers (2)

Saurabh Rajpal
Saurabh Rajpal

Reputation: 1557

After testing and playing around in Fiddle, I could figure out that basically the line "$('#textAreaComplemento').val().length" is finding out the number of characters only (and not counting the number of spaces, like in this case there are 4 spaces before return false ). Hence, when you copy, paste something (say your code which has 5 spaces in between it), then the user can enter only after deleting 6 letters which makes the total count as 194 (200-6) + 5 (spaces) + space for one letter to be entered.
You can probably use something like this to avoid any spaces or carriage returns being counted by the browser and just consider the letters:

$(function () {
$('#test').keyup(function () {
    var x = $('#test').val();

    var newLines = x.match(/(\r\n|\n|\r)/g);
    var addition = 0;
    if (newLines != null) {
        addition = newLines.length;
    }

    $('#length').html(x.length + addition);
})

})

Upvotes: 4

Nibin
Nibin

Reputation: 3960

Something like this might help u mate.. :)

  $("#textAreaComplemento").bind("keyup change input propertychange", function (e) {
        calculaCaracteresRestantes();
    });

Fiddle

Upvotes: 0

Related Questions