textarea制限文字数入力

1972 ワード


<form action="" id="commentForm" name="commentForm" method="POST">
    <textarea id="commentText" name="commentText" rows="4" cols="50" maxNum="500"></textarea>
    <p class="c-tip"><input id="subBtn" class="btn" type="submit" value="  " disabled="true"></input> 1~500   ,     <span id="num" class="number">500</span> </p>
</form>

textarea{width:98%;height:80px;_width:490px;overflow-y:auto;}
.c-tip .number{color:#f56600;}
.c-tip .btn{float:right;}

   var commentText = document.getElementById('commentText'),
        num = document.getElementById('num'),
        maxNum = commentText.getAttribute('maxNum'),
        subBtn = document.getElementById('subBtn');
    subBtn.setAttribute('disabled',true);
    
    var changeFn = function(){
        var val = commentText.value;
        if(val){
            val = val.replace(/^\s+|\s+$/g,'');
        }
        if(val.length == 0){
            subBtn.setAttribute('disabled',true);
        }else{
	        if(val.length > maxNum){
	            subBtn.setAttribute('disabled',true);
	        }else{
	            subBtn.removeAttribute('disabled');
	        }
        }
        num.innerHTML = (maxNum - val.length);
    };
    if(/MSIE ([^;]+)/.test(navigator.userAgent)){
           commentText.onpropertychange = changeFn;
    }else{
        commentText.addEventListener('input',changeFn,false);
    }
    commentText.onkeyup = changeFn;