How to set max length for Span and Div elements ?
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.
To restrict user from entering more characters compare to maxlength in span or div element, you can do following using javascript and jquery : You can add keydown event listener on div or span element and add following functions in event listener. 1: Using javascript substring method. $("#div-element").
Use $("input"). attr("maxlength", 4) if you're using jQuery version < 1.6 and $("input"). prop("maxLength", 4) if you are using jQuery version 1.6+.
There are the
max-height / max-width
CSS properties that will limit the width for block level elements (i.e. not spans). Reference
Note that they are not supported by IE 6.
input and textarea html tags have maxlength attribute but div and span element don't have. To restrict user from entering more characters compare to maxlength in span or div element, you can do following using javascript and jquery:
You can add keydown event listener on div or span element and add following functions in event listener.
1: Using javascript substring method.
$("#div-element").on("keydown", function () {
var value = $("#div-element").val();
if (value.length > maxlength) {
$("#div-element").val(value.substring(0, maxlength));
}
}());
2: Returning false on event.
$("#div-element").on("keydown", function () {
var value = $("#div-element").val();
if (value.length > maxlength) {
return false;
}
}());
These both have followup issues which should be handled as well ie substring method change the cursor position, in keydown method we need to check which key is pressed, otherwise it return false even on backspace or delete key.
When the word contained is too large the div or span may overflow:
<div style="width: 80px; overflow: hidden;" >hhhhhhheeeeeellllllllllooooo</div>
If long words are the problem a CSS3 solution could be:
style="width: 80; word-wrap: break-word;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With