jquery擴展實現input框字符長度限制中文2個字符,英文1個字符


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>

$(function () {
$('input[type="text"]').on('input', function (e) {
var $that = $(this);
var limitLen = $that .attr("maxcodelength") //定義所需字節數
$that.attr('maxlength',limitLen);
setTimeout(function(){
var value = $that.val(),
reg = /[\u4e00-\u9fa5]{1}/g, //中文
notReg = /\w{1}/g; //非中文
var resultCn = value.match(reg);
var resultEn = value.match(notReg);
if(resultCn){
limitLen = limitLen - (resultCn.length*2);
}
if(resultEn){

limitLen = limitLen - resultEn.length;
}
if(limitLen<=0){
var finalLen = value.length+limitLen;
value = value.substring(0,finalLen);
$that.attr('maxlength',limitLen);
$that[0].value = value;
}
},0);

});
});
</script>
</head>
<body>
請輸入:<input type="text" maxcodelength="10">
<input type="text" maxcodelength="5">
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM