Reputation: 141
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
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
Upvotes: 2
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