Makudex
Makudex

Reputation: 1082

Maxlength for DIV like Textarea

I want to set the maximum text-length of the div.

I have this HTML code here:

<div contentEditable=true data-ph="Subject of this message" maxlength = "10" id = "discussionsubject">
</div>  

In which I made the DIV to act like textarea. Now, I tried to set it's maxlength by 10 but it doesn't worked.

Also tried this few codes found in other SO questions which seems not working fine with me:

 var myDiv = $('#discussionsubject');
 myDiv.text(myDiv.text().substring(0,10));

Also tried this code but still doesn't work:

$("div#discussionsubject).text(function(index, currentText) {
    return currentText.substr(0, 10);
});

Please, need help..

Upvotes: 1

Views: 457

Answers (2)

user2575725
user2575725

Reputation:

Problem with your second code is that you are missing closing quotes:

$("div#discussionsubject )
                        ^ -- required (")

Sample demo:

$(function() {
  $('div.edit-box').text(function(_, txt) {
    return txt.substring(0, +$(this).data('length'));
  });
});
div.edit-box {
  border: 1px ridge grey;
  height: 50px;
  margin: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-length="10" class='edit-box'>
  Hello there everyone ...
</div>
<div data-length="20" class='edit-box'>
  Good day !! This goes another line ...
</div>

Upvotes: 0

user3497034
user3497034

Reputation:

I hope following code may help you:

//Maximum number of characters
var max = 10;

$('#editable_div').keydown(function(e) {
    var keycode = e.keyCode;

    //List of keycodes of printable characters from:

        var printable = 
        (keycode > 47 && keycode < 58)   || // number keys
        keycode == 32 || keycode == 13   || // spacebar & return key(s) (if you want to allow carriage returns)
        (keycode > 64 && keycode < 91)   || // letter keys
        (keycode > 95 && keycode < 112)  || // numpad keys
        (keycode > 185 && keycode < 193) || // ;=,-./` (in order)
        (keycode > 218 && keycode < 223);   // [\]' (in order)

    if (printable) {

        return $(this).text().length <= max; 
    }
});

UPDATE
For managing copy and paste actions, you need to manage following event handler:

 document.getElementById("discussionsubject").addEventListener("input", function () {
            alert("input event fired");
        }, false);

Now merge the logic from first code block into updated event handler.

Upvotes: 2

Related Questions