In the development of Web pages, the string in the form too long and beyond the specified length will cause some unnecessary trouble, such as: User registration system restrictions on the user name only 8 English characters, but the user entered 10 or more character, it may cause the nickname page display the wrong line, or the nickname is truncated problem. Here's a solution to limit the length of a string:
1, by using JavaScript native method of getting properties:
#id. getattribute ("Data-length");
To determine the limit length of the input box.
2, compare the length of the input with the limit length property of the input box:
if (Input length > attribute length) { // over length auto intercept }
HTML code:
<input type= "Text" data-length= "6" id= "Limitlength" name= "Iname"/>
JavaScript method:
var maxLength = function (tthis) { var _v = tThis.value.replace (Maxregex, '), // get input text (remove spaces) _vlen = _v.length, Datalength = Tthis.getattribute (' data-length '), Get the limit length Datamodel = Tthis.getattribute (' Data-model ' ), Sublen = Datalength; if (_vlen > Datalength) {Tthis.value /span>= _v.substr (0,sublen); // judging length, exceeding length automatically intercept
Complete JavaScript code:
varLimitlength = document.getElementById (' limitlength ')); varMaxregex =/\s+/g;//regular expression for removing spaces varMaxLength =function(tthis) {var_v = TThis.value.replace (Maxregex, "),//get input text (remove spaces)_vlen =_v.length, Datalength= Tthis.getattribute (' data-length '),//Get limit lengthDatamodel = Tthis.getattribute (' Data-model ')), Sublen=datalength; if(_vlen >datalength) {Tthis.value= _v.substr (0,sublen);//judging length, exceeding the length of the automatic intercept}} Limitlength.onblur=function() {maxLength ( This); } limitlength.onkeyup=function() {maxLength ( This); } Limitlength.onfocus=function() {maxLength ( This); }
View Code
If you are interested, please click on the recommended amount, thank you!
Sweep code attention to the public number:
Limit string length