Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a textarea with character limit highlighting like Twitter?

Twitter's submit tweet textbox highlights the characters that are over the character limit:

As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?

like image 312
Berat Şen Avatar asked May 20 '14 00:05

Berat Şen


2 Answers

You'll find the necessary solution and required code here:

How to insert <em> tag when exceeding 140 limit i.e. going negative?

...and here:

REGEX - Highlight part over 19 chars

Your question appears to be duplicitous.

Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).

Here's the code as per Simon Kuang's recommendation (see comments):

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <h3>Your text here</h3>
   <div contenteditable="true" id="myDiv">edit me
  </div>
  <p>
    <h3>Stuff over 19 characters</h3>
  <div id="extra">
  </div>
  <p>
    <h3>Sample output</h3>
    <div id="sample">

  </div>
</body>
</html>

CSS:

.highlight {
 color:red;
}

JavaScript:

$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];

    $('#extra').html(extra);

    var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
    $('#sample').html(newContent);
  });
});
like image 163
Clarus Dignus Avatar answered Sep 18 '22 09:09

Clarus Dignus


Here is the example, show alert when the limit is reached and thereafter highlight all the characters entered.

$(document).ready(function() {
  var input = $('#text_text');
  var warning = $('#warning');
  var char_limit = 30;
  input.on('keyup', function() {
    var val = $(this).val();
    if (val.length > parseInt(char_limit)) {
      alert("limit reached");
      warning.html('hello').css('display', 'block');
      l = val.length
      var input = document.getElementById("text_text");
      input.setSelectionRange(char_limit, l);
      input.focus();
    } else {
      warning.css('display', 'none');
    }
  });

});
#warning {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test_box">
  <textarea name="msg" cols="50" rows="5" id="text_text"></textarea>

  <div id="warning"></div>
</div>
like image 25
Sudhanshu Avatar answered Sep 20 '22 09:09

Sudhanshu