how to limit number of characters in a textarea field processing php?

允我心安 提交于 2019-12-03 12:37:23

You can limit this by setting maxlength attribute on textarea tag like <textarea maxlength="120"></textarea> in HTML and additionally "cut" input string in PHP by substr() function.

toni_lehtimaki

As mentioned by s.webbandit you can use maxlength, but note that this is a new feature introduced in HTML5, as W3 Schools article about <textarea>, so "bulletproof" solution needs Javascript. So maxlength is not supported in Internet Explorer until version 10 and in Opera not at all.

Here is one approach that uses Javascript to help you out:

<script language="javascript" type="text/javascript">
   function charLimit(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
      limitField.value = limitField.value.substring(0, limitNum);
  } else {
      limitCount.value = limitNum - limitField.value.length;
       }
    }
</script>

You can then use it like this (original source):

    <textarea name="limitedtextarea" onKeyDown="charLimit(this.form.limitedtextarea,this.form.countdown,100);">
    </textarea>

This should get you going.

This is a very easy way to limit the length of a text area via JavaScript.

text area field:

<input class='textField' type='text' NAME='note1' value='' onkeyup='charLimit(this, 40);'>

JavaScript function:

function charLimit(limitField, limitNum) {
  if (limitField.value.length > limitNum) {
   limitField.value = limitField.value.substring(0, limitNum);}
}

When the user types past 40 characters it just removes them.

I've tried a lot of different ways to limit text in textareas, and the best I have found (client side) is with the jQuery.Maxlength.js plugin. Simple quick and covers them all!

Step 1. Include Maxlength plugin script

<script language="javascript" src="jquery.maxlength.js"></script>

Step 2. Add maxlength attribute to

<textarea maxlength="35" 
    rows="5" cols="30" name="address"></textarea>

Step 3. Initialize plugin

<script type="text/javascript">
    $(document).ready(function($) {
             //Set maxlength of all the textarea (call plugin)
             $().maxlength();
    })
</script>

https://github.com/viralpatel/jquery.maxlength

ufuk
<script type="text/javascript">
        $(document).ready(function(){
        var maxChars = $("#sessionNumtext");
        var max_length = maxChars.attr('maxlength');
        if (max_length > 0) {
            maxChars.bind('keyup', function(e){
                length = new Number(maxChars.val().length);
                counter = max_length-length;
                $("#sessionNum_counter").text(counter);
            });
        }
    });
</script>

<textarea name="sessionNumtext" id="sessionNumtext" maxlength="20" type="text"></textarea>
kalan karakter sayısı: <span id="sessionNum_counters">20</span>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!