The textarea maxlength attribute does not work correctly in all browsers

I want to limit the text box to 500 characters. For this, I used the maxlength attribute, but there is a compatibility problem in different browsers. To solve this problem, I used javascript function

function checkLength(fieldName,limit){

            if(fieldName.value.length >= limit){

                fieldName.value  = fieldName.value.substring(0,limit);
            }
        }

I call this function in two events onKeyDown and onKeyUp . This fixes my problem somewhat, but when I copy and paste a line longer than 500 characters, it displays all the text and then trims to 500 on the keyboard. Is there a way to show exactly 500 characters when copying, rather than flickering.

+4
source share
2 answers

jquery, , :

script:

$('textarea').on('paste keyup keydown', function (event) {
 var element = this;
  setTimeout(function () {
   if($(element).val().length > 500)
    {
     if(event.type=="paste"){
      $(element).val($(element).val().substr(0,500))    
     }else{
      $(element).val($(element).val().slice(0,-1));
     }
      alert("excceded more then 500 characters");
    }else{
     return true;
    }
 }, 100);
});

: http://jsfiddle.net/2Qxh9/

+1

- :

            <script language="javascript" type="text/javascript">
            function limitText(limitField, limitCount, limitNum) {
                if (limitField.value.length > limitNum) {
                    limitField.value = limitField.value.substring(0, limitNum);
                    alert("your message exceeds the limit");
                } else {
                    limitCount.value = limitNum - limitField.value.length;
                }
            }
            </script>

            <form name="myform" action="">
                <textarea id="t1" name="description" onpropertychange="limitText(this.form.description,this.form.countdown,500);"  OnInput="limitText(this.form.description,this.form.countdown,500);" onKeyDown="limitText(this.form.description,this.form.countdown,500);" rows="20" cols="40">
                </textarea><br>
               <font size="1">(Maximum characters: 500)<br>
                You have <input readonly type="text" name="countdown" size="3" value="10"> characters left.</font>
            </form>
0

All Articles