Vinod
Vinod

Reputation: 141

max limit set in paragraph tag with contentEditable true

I have a paragraph tag, which is editable and I want to set max limit on that. After max limit, character should not be type. I tried, but not working.

<p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hhhhh</p>

jquery is:

function limitMessage(id,e){
        var tval = $('#'+id).val(),
            tlength = tval.length,
            set = 10,
            remain = parseInt(set - tlength);
        if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
            $('#'+id).val((tval).substring(0, tlength - 1))
        }
    }

Upvotes: 1

Views: 176

Answers (2)

Umair Khan
Umair Khan

Reputation: 1752

Please try this.

function limitMessage(id, e) {
  var tval = $('#' + id).html(),
    tlength = tval.length,
    set = 10,
    remain = parseInt(set - tlength);
  if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
    $('#' + id).html((tval).substring(0, set + 1));
    e.preventDefault();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hhhhh</p>

Explanation

  1. You were using .val instead of .html.
  2. When you were inserting the string back, the cursor got reset to start of string and new char was added and a char from end of string was trimmed. To tackle this, I added e.preventDefault to stop the char from getting added.

Upvotes: 2

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 1128

You forgot the jQuery CDN and you're using p instead of input, then you need to use html() instead of val() because the p element doesn't expect value.

And you don't need to write $(this).val((tval).substring(0, tlength - 1)) because it will return to the begining of the sentence, so just use a preventDefault() to stop writing.

Try this :

function limitMessage(id, e) {
  var tval = $('#' + id).html(),
    tlength = tval.length,
    set = 10,
    remain = parseInt(set - tlength);
  if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
    e.preventDefault();
  }
}
body {
  background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hello</p>

Upvotes: 3

Related Questions