通过javascript验证Textarea

时间:2016-11-11 05:31:48

标签: javascript textarea radio

有2种单选按钮。

如果检查sms按钮,则textarea的maxlength设置90个字节

如果检查lms按钮,则testarea的maxlength设置2000个字节

我们可以查看我在textarea的'totalWordLimit'上放了多少文本

但有问题

如果我通过副本放置许多文本&粘贴,textarea变得禁用

当我更改单选按钮时,计数也不会初始化。

我需要在此代码中修复哪些内容?

<script type="text/javascript">

var setTotalNumberOfWordCounter = "90";

function displayWordCounter(){
var getTextValue = document.smsForm.msg.value;  // Get input textarea value
var getTextLength = getTextValue.length;   // Get length of input textarea value
var one_char = "";
var rbyte = 0;
var rlen = 0;
for(var i=0; i<getTextLength; i++){
	one_char = getTextValue.charAt(i);
	if(escape(one_char).length > 4){
	    rbyte += 2;                             // special language(2Bytes)
	}else{
	    rbyte++;                                // 1Byte
	}

	if(rbyte <= setTotalNumberOfWordCounter){
	    rlen = i+1;                             //return text count
	}
}
if(rbyte > setTotalNumberOfWordCounter){     //compare this length with total count
        getTextValue = getTextValue.substring(0,setTotalNumberOfWordCounter);
        document.smsForm.msg.value =getTextValue;
        return false;
}
	document.smsForm.totalWordLimit.value = (setTotalNumberOfWordCounter-rbyte);
	var tt = document.getElementById("Textarea");
	
	if(document.smsForm.totalWordLimit.value === "0"){			
		tt.value = tt.value.substring(0, tt.value.length-1);
	}
}

</script>

<script type="text/javascript">
    function ShowHide() {        
        var Textarea = document.getElementById("Textarea");         
        if(document.getElementById('sms').checked) {
        	setTotalNumberOfWordCounter = "90";
        }else if(document.getElementById('lms').checked) {
    		setTotalNumberOfWordCounter = "2000";
        }
         
    }    
    
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="sms" id="sms" onclick="ShowHide()" value="ss" checked>SMS
<input type="radio" name="lms" id="lms" onclick="ShowHide()" value="ll"> LMS
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" ></textarea>
									
<script type="text/javascript">
				document.write("<div class='total_count'>total remaining Charatctor: <input type='text' class='show_count' name='totalWordLimit' size=4 readonly value="+setTotalNumberOfWordCounter+"></div>");
</script>

1 个答案:

答案 0 :(得分:0)

试试这个

function ShowHide() {        
    var Textarea = document.getElementById("Textarea");         
    if(document.getElementById('sms').checked) {
        Textarea.setAttribute("maxlength", "90");
    }else if(document.getElementById('lms').checked) {
        Textarea.setAttribute("maxlength", "2000");
    }

}   

并在textarea元素中尝试onpaste函数

<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" onpaste="return displayWordCounter();"></textarea>