[Javascript] 글자수 체크 / 글자수 제한

2016. 6. 10. 11:33프로그래밍/Javascript & JQuery

 function chkword(obj, maxByte) {

 

        var strValue = obj.value;

        var strLen = strValue.length;

        var totalByte = 0;

        var len = 0;

        var oneChar = "";

        var str2 = "";

 

        for (var i = 0; i < strLen; i++) {

            oneChar = strValue.charAt(i);

            if (escape(oneChar).length > 4) {

                totalByte += 2;


            } else {

                totalByte++;


            }

 

            if (totalByte <= maxByte) {

                len = i + 1;


            }

        }

 

        if (totalByte > maxByte) {

            alert(maxByte + "자를 초과 입력 할 수 없습니다.");

            str2 = strValue.substr(0, len);

            obj.value = str2;

            chkword(obj, 4000);


        }

    }


<input type="text" id="byteInfo" name="title"

        onkeyup="chkword(this, 5)" />


펌 : http://www.devblog.kr/r/8y0gFPAvJ2j8MWIVVXucyP9uYvQegfSVbY5XNDBmy