Skip to content
Advertisement

How to show alert message if html textarea length is larger then specified?

I want to show an alert message if the user type more than 1000 characters or copy past more than 1000 characters. For that, I am using following JS code but somehow it’s not working.

HTML code:

<div class="form-group">
    <label for="">Werk-Beschreibung</label>
    <textarea id="limit" maxlength="1000" name="werk_beschreibung" maxlength="1000" cols="30" rows="10" class="form-control"><?php echo escape($werk_beschreibung); ?></textarea><span class="counter"></span>
</div>

JS code:

$("#limit").on('input', function() {
    if($(this).val().length >=1001) {
        alert('you have reached a limit of 1000');       
    }
});

What am I doing wrong here?

Advertisement

Answer

Here’s a code from How can I bind to the change event of a textarea in jQuery?

$('#textareaID').bind('input propertychange', function() {
    if (this.value.length > 1000) {
        $("#textareaID").val($("#textareaID").val().substring(0,1000));
        alert("stop");
    }
});

Here’s the working fiddle with 1000 character limit.

Fiddle: https://jsfiddle.net/ofpn88mc/3/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement