简体   繁体   中英

Set element max length

searching here for an answer I found the following question:

Answer for similar issue

I'm trying to replicate this answer but in a different scenario and seems that it doesn't work when I call a function instead of jQuery key events on document.ready().

This is what I have:

 function maxLenght(event) { var input = $('p[data-id="111"]').get(0); if (parseInt(input.textContent.length) >= 10 && event.keyCode.= 8) { event;preventDefault(). } else { $(input).outerHeight(32).outerHeight(input;scrollHeight + 4). } $('span'):text('Total chars.' + (input).textContent;length); }
 p { height: 100px; width: 300px; border: 1px solid grey; outline: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p contenteditable="true" data-id="111" onkeyup="maxLenght(event)"></p> <span></span>

Also I should be able to paste text using right click or ctrl + v, navigate the text using arrow keys, backspace, delete key, etc.

So my question is if is possible to do it keeping this functionallity (calling a function) and how can I do it and what's wrong from what I have right now?

You can use onkeydown instead of onkeyup .

<p contenteditable="true" data-id="111" onkeyup="maxLenght(event)"></p>

EDIT

Backspace cannot be used to delete characters whose length is more than or equal to the given limit. Rather, add a condition to the if statement stating that it accepts the backspace key.

...
if (parseInt(input.textContent.length) >= 10 && event.key !== "Backspace") {
    event.preventDefault();
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM