How can I make textarea with a character highlight, like Twitter?

Twitter submit tweet textbox highlights characters that exceed the character limit:

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

+4
source share
3 answers

Here you will find the necessary solution and the required code:

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

... and here:

REGEX - Highlight more than 19 characters

Your question seems two-faced.

Note. I did not have the opportunity to post the above links as a comment (i.e. reputation-dependent privileges).

(. ):

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);
  });
});
+3

, , , .

$(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>
Hide result
+1

Try this (Figure)

HTML

<data></data><br />
<textarea maxlength="20" placeholder="20 character limit"></textarea>

Js

$(function () {
    $(document).on("keyup", "textarea", function (e) {
        if ($(e.target).val().length >= 20) {
            $("data").text($(e.target).attr("placeholder"))
            .fadeIn(1000).fadeOut(9000);
        };
    });
});

jsfiddle http://jsfiddle.net/guest271314/8RScd/

0
source

Source: https://habr.com/ru/post/1541196/


All Articles