3

可能重复:
onKeyPress 事件在 Firefox 中不起作用

<div><textarea maxlength="1000" rows ="5" cols ="5" 
   style="width:398px; height: 175px; overflow: auto; padding: 4px !important" 
   name="body" value="" id="body" onkeypress="imposeMaxLength(this, 10);"  
   onPaste="imposeMaxLength(this, 10);" /></textarea></div>
<script>
function imposeMaxLength(field, MaxLen){

    if (field.value.length > (MaxLen-1)) {
        alert("It cannot exceed " + MaxLen + " characters.");
        field.value= field.value.substr(0, (MaxLen);
    }
}
</script>
4

1 回答 1

1

Your markup isn't right

<textarea ... /></textarea>

is invalid, it should be

 <textarea ... ></textarea>

And try this, it's working

<div>
  <textarea maxlength="1000" 
            rows="5"
            cols="5" 
            style="width: 398px; height: 175px;overflow: auto; padding: 4px !important"              
name="body" 
            id="body" 
            onkeypress="imposeMaxLength(this, 10);"
            onpaste="imposeMaxLength(this, 10);" >
    </textarea>
</div>

<script type="text/javascript">
function imposeMaxLength(field, MaxLen){
    if (field.value.length > (MaxLen-1)) {
        alert("It cannot exceed " + MaxLen + " characters.");
        field.value = field.value.substr(0, (MaxLen));
   }
}
</script>
于 2012-11-12T11:55:18.600 回答