Add counter to textarea input
I have the following script which serves the purpose but would like to add a counter to visually inform the user of remaining characters.
script
function limit(element, max_chars)
{
if(element.value.length > max_chars)
element.value = element.value.substr(0, max_chars);
}
html
<textarea onkeyup="javascript开发者_C百科:limit(this, 150)" onblur="limit(this,150)" name="message" rows="4" style="width:99%; margin: 0;" class="unfocusinput"></textarea>
You can add a couple of lines to your limit function that get some element and update its content based on the value of element.value.length.
html:
<textarea ...></textarea>
<span id="contentLen">count goes here</span>
javascript:
function limit(element, max_chars)
{
if(element.value.length > max_chars)
{
element.value = element.value.substr(0, max_chars);
}
document.getElementById ('contentLen').innerHTML = element.value.length;
}
Friend;
You can use this function on onKeyDown
if(document.getElementById(element).value.length==limit && event.keyCode!=8)
document.getElementById(element).blur();
PS : keycode 8 is backspace.
script
function limit(element, max_chars, counter)
{
if(element.value.length > max_chars)
element.value = element.value.substr(0, max_chars);
document.getElementById(counter).innerHTML = element.value.length - max_chars;
}
html
<textarea onkeyup="javascript:limit(this,150,'someCounter')" onblur="limit(this,150,'someCounter')" name="message" rows="4" style="width:99%; margin: 0;" class="unfocusinput"></textarea>
<span id"someCounter">150</span> chars left
Here's a jQuery plugin that does just that.
精彩评论