Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maxlength for Div and Span elements

Tags:

html

maxlength

How to set max length for Span and Div elements ?

like image 201
Puru Avatar asked Jun 24 '10 08:06

Puru


People also ask

What is the use of Maxlength attribute?

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.

How do I limit the size of a div?

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").

How do you add a Maxlength in CSS?

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+.


3 Answers

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.

like image 77
Pekka Avatar answered Oct 21 '22 22:10

Pekka


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.

like image 37
Yashashvi Avatar answered Oct 21 '22 21:10

Yashashvi


When the word contained is too large the div or span may overflow:

<div style="width: 80px; overflow: hidden;" >hhhhhhheeeeeellllllllllooooo</div>
  • You can wrap a span with a div. It will cut the content if there are no spaces in the text but it will prevent overflow from happening.

If long words are the problem a CSS3 solution could be:

style="width: 80; word-wrap: break-word;"

like image 2
PbxMan Avatar answered Oct 21 '22 22:10

PbxMan