1

I'm using an answer given here Count textarea characters but need to modify it to count down characters in a text field input AND change colour as it hits certain count down numerical limits, to give the user some form of warning they are approaching the field limitation.

This is what I have put together so far, on my own. It actually works! (Amazingly). First, this is what I started with:

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        $("#count_4_1").text("Characters remaining: " + (2550 - $(this).val().length));
    });
});

And this is what I have re-invented it as:

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        if (2550 - $(this).val().length >= 501) {
            $("#count_4_1").text("Characters remaining: " + (2550 - $(this).val().length));
        } else if ((2550 - $(this).val().length <= 500) && (2550 - $(this).val().length >= 101)) {
            $("#count_4_1").text("<span style=\"color: #55a500;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        } else if (2550 - $(this).val().length <= 100) {
            $("#count_4_1").text("<span style=\"color: #ff0000;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        }
    });
});

And this is what amazingly works. With one exception - and here comes the question. I know next to nothing about JS. When the character number read-out is between 2550 and 500 the display if fine. When the character read-out becomes 500 to 100 the read-out shows:

<span style="color: #55a500;">Characters remaining: 499</span>

So how do I get the JS to actually kick the css into proper display effect, instead of simply echoing out on the page??

If relevant, jQuery is in use.

Community
  • 1
  • 1
Cassandra
  • 284
  • 4
  • 18

4 Answers4

2

Alternatively and just for fun: you may like this more generic, css/data-atributes and no jquery approach:

[].slice.call(
  document.querySelectorAll('div[data-isRestrictedTextArea]')
).forEach(
  function(el) {
    var txtarea = el.querySelector('textarea')
       ,cntr = el.querySelector('div[data-iscounter]');
    
    cntr.setAttribute('data-maxlen', el.getAttribute('data-maxlen'));
    txtarea.onkeyup = count;
  }  
);

function count(e) {
  var len  = this.value.length,
      cntr = this.parentNode.querySelector('div[data-iscounter]'),
      maxl = this.parentNode.getAttribute('data-maxlen'),
      warn = maxl-Math.floor(0.2*maxl), // 80%  
      stop = maxl-Math.floor(0.1*maxl); // 90%

  cntr.setAttribute('data-ncharacters', len);
  cntr.className = len >= stop ? 'stop'
                   : len >= warn ? 'warn' 
                   : '';
  // truncate if len>=maxlen
  this.value = len >= maxl ? this.value.substr(0, maxl) : this.value;
  // set attribute for reporting
  cntr.setAttribute('data-ncharacters', len >= maxl ? maxl : len);
  return;
}
body {font: 12px/15px normal verdana,arial;}

div[data-isrestrictedTextarea] {
  display: inline-block;
  margin-top: 1em;
}

div[data-iscounter] {
  color: green;
  background-color: #eee;
}

div[data-iscounter]:before {
  content: 'you typed 'attr(data-ncharacters)' characters';
}

div[data-iscounter]:after {
    content: ' [max 'attr(data-maxlen)' characters]';
}

div[data-iscounter].warn {
  color: orange;
}

div[data-iscounter].stop {
  color: red;
}
<div data-isrestrictedTextarea="1" data-maxlen="15">
  <textarea placeholder="start typing" rows="2" cols="60"></textarea>
  <div id="cnt_cnttxt" data-iscounter="1" data-ncharacters="0"></div>
</div>

<div data-isrestrictedTextarea="1" data-maxlen="100">
  <textarea placeholder="start typing" rows="5" cols="60"></textarea>
  <div id="cnt_cnttxt" data-iscounter="1" data-ncharacters="0"></div>
</div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

From the jQuery page, regarding .text (here: http://api.jquery.com/text/):

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML

(Emphasis mine.)

You need to append your text to the page with the .append function (here: http://api.jquery.com/append/), not place it in with .text.

Additionally, if there is no other content in the element in which you are placing the new string, you can simply use .html (here: http://api.jquery.com/html/) to replace the entire contents of the container with your new string.

Mark
  • 861
  • 9
  • 17
  • @Pointy Yep, thanks. Was already editing to add that in after re-checking the code to see if it looked like .html might work. – Mark Feb 09 '15 at 14:32
1

Since you're using HTML tags, you cannot set them using the .text() method. Use the .html() method instead:

I've added a little clean up code.. set the calculation in a variable to make it cleaner...

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        var diff = (2550 - $(this).val().length);
        if (diff >= 501) {
            $("#count_4_1").html("Characters remaining: " + diff);
        } else if ((diff <= 500) && (diff >= 101)) {
            $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + diff + "</span>");
        } else if (diff <= 100) {
            $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + diff + "</span>");
        }
    });
});
LcSalazar
  • 16,524
  • 3
  • 37
  • 69
  • Thank you, LcSalazar, your explanation and code tidy up has sorted the matter out nicely for me. Much appreciated. Thank you to everyone else who answered - there were no wrong answers but sadly I can only mark one as the accepted answer. I marked the one that best fit what I was doing and helped in tidying up the code that was doing it. However there is another question now, but I'll ask that in another post! – Cassandra Feb 09 '15 at 15:27
1

There are many ways to do it:

first create a markup in your HTML as:

<div id="warning"></div> /* Exactly above or below your text box */

Next in you JS you can use:

Javascript:

var html= "<span style='color: #55a500;'>Characters remaining: 499</span>";
document.getElementById("warning").innerHtml(html);

using Jquery:

var html= "<span style='color: #55a500;'>Characters remaining: 499</span>";
document.getElementById("warning").innerHtml(html);
$('#warning').html(html);

or

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        if (2550 - $(this).val().length >= 501) {
            $("#count_4_1").html("Characters remaining: " + (2550 - $(this).val().length));
        } else if ((2550 - $(this).val().length <= 500) && (2550 - $(this).val().length >= 101)) {
            $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        } else if (2550 - $(this).val().length <= 100) {
            $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        }
    });
});
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28