Dynamic Text limit when users writes in a textbox (HTML)
I need to implement in Html/javascript (or php is possible) a script which works like twitter, when the user writes text in 开发者_运维技巧a field a label change showing the characters left.
Can you help me with a simple and easy script example?
<script>
function checkCharCount(textfield){
if(textfield.value.length > 300) textfield.value = textfield.value.substr(0, 300);
document.getElementById("charCounter").innerHTML = 300 - textfield.value.length;
}
</script>
<textarea class="input" name="REMARK" rows="5" cols="45" maxlength="300" wrap="virtual" onKeyUp="checkCharCount(this);"></textarea>
<div><span id="charCounter">300</span> characters left.</div>
Tim Down made me curious about the methods of detecting paste where it's done with a mouse and not the keyboard. After spending an hour on the net and trial-and-error with a test-page I have this RATHER SIMPLE BUT EFFECTIVE cross-browser [as much as it gets] solution to offer, which satisfies me in functionality, but may not satisfy javascript purists in approach. (hey, just trying to help)
<head>
<script>
function checkCharCount(){
textfield = document.getElementById('remark');
//if(textfield.value.length > 300) // does not register length change until the next paste or keyup
textfield.value = textfield.value.substr(0, 300);
document.getElementById("charCounter").innerHTML = 300 - textfield.value.length;
}
</script>
</head>
<body>
<textarea id="remark" class="input" name="remark" rows="5" cols="45" wrap="virtual" onkeyup="checkCharCount();" onpaste="setTimeout(checkCharCount, 20);"></textarea>
<div><span id="charCounter">300</span> characters left.</div>
</body>
see references and browser compatibility notes at http://www.quirksmode.org/dom/events/cutcopypaste.html and check out their Demo Page which is worth bookmarking, in my subjective opinion
I'd take a JQuery Plugin like this one. To do it with PHP is possible, but would be quite.. well.. wrong. Since PHP runs on the server you'd have to send / receive to / from the server with every keydown. Javascript runs client-side, so this extra payload isn't needed. Hover you can specify the max value in PHP, send it to the client in the original response and use it in your client side javascript.
精彩评论