2013-11-25 57 views
1
function countChar(val) 
    { 
    var xy=document.getElementsByID(val).value; 
    var len = xy.length; 
    if (len >= 2) { 
     val.value = val.value.substring(0, 1); 
    } else { 
     document.getElementsByID(val).value=(1 - len); 
    } 
} 

<input type="text" name="mytextbox" id="mytextbox" 
     onKeyUp="countChar(this.value)" size="1" maxlength="1" value="" /> 

回答

0

讓你的HTML這樣的:

<input type="text" name="mytextbox" id="mytextbox" 
    onKeyUp="countChar(this)" size="1" maxlength="1" value="" /> 

和JS會是這樣的:

function countChar(that) 
{ 
    var xy = that.value; 
    var len = xy.length; 
    if (len >= 2) { 
    that.value = that.value.substring(0, 1); 
    } else { 
    that.value=(1 - len); 
    } 
}