I had been given a requirement from client saying limit the textarea – 200 characters in English, it is approximate 66 Chinese characters for UTF8.
I wonder how do I check them whether it i开发者_C百科s chinese character or english character and calculating them in the sense of maximum length ?
Alright so I found a way (UTF-8 based) and somehow useful for me. But when I thought of client side, it was somehow still "yucks" ever since they are still able to edit it when inspect the dom element.....
Please advice me. Thanks
Code: My textarea and count box:
<textarea class="message" name="quiz_answer" cols="30" rows="4"></textarea><br />
<span class="countdown"></span>
Jquery document ready:
updateCountdown();
$('.message').attr('maxLength','25');
$('.message').keyup(updateCountdown);
updateCountdown function():
var previous = '';
var current = '';
//Count textarea words
function updateCountdown() {
var countMe = $(".message").val();
if(previous==''){
previous = countMe;
current = countMe;
}else{
current = countMe;
}
var escapedStr = encodeURI(countMe);
if (escapedStr.indexOf("%") != -1) {
var count = escapedStr.split("%").length - 1;
if (count == 0) count++ //perverse case; can't happen with real UTF-8
var tmp = escapedStr.length - (count * 3);
count = count + tmp;
} else {
count = escapedStr.length;
}
// 200 is the max message length
var remaining = 200 - count;
$('.countdown').text(remaining + ' characters remaining.');
if(remaining < 0){
$(".message").val(previous);
}else{
previous = current;
}
}
精彩评论