Question

I try to use all here in this combination:

<SCRIPT LANGUAGE="JavaScript">

 function CountLeft(field, count, max) 
 {
     if (field.value.length > max)
         field.value = field.value.substring(0, max);
     else
         count.value = max - field.value.length;
 }

</SCRIPT>
<input name="text" onKeyDown="CountLeft(this.form.text, this.form.left,50);"
                   onKeyUp="CountLeft(this.form.text,this.form.left,50);"  onKeyPress="return entsub(event)">


<input readonly type="text" name="left" size=3 maxlength=3 value="50">  
characters left

But the enter key to submit does not work here, can anyone tell me how I can fix that? Oh and, I am trying to make a counter here.

Thanks!

Was it helpful?

Solution

Actually, you don't need all these keyhandlers. One keydown handler would be sufficient.

The here given function keyhandler stops updating the text input value after max is reached and submits the form if the key pressed was enter. You can find an example @ http://jsfiddle.net/KooiInc/2hrt7/.

<input type="text" onkeydown="return keyhandler(this,event,50)"/>

now keyhandler looks like this:

function keyhandler(obj,e,max) {
    e = e || event;
    max = max || 50;
    console.log(e.keyCode);
    if (e.keyCode === 13) {
        return document.forms[0].submit();
    }
    if (obj.value.length >= max && e.keyCode>46) {
        return false;
    }
    return true;
}

By the way, you are aware of the maxlength attribute of a text input field?

OTHER TIPS

I needed that script too and the one given by Kooilnc didn't really work for me. I used this:

function keyhandler(obj,e,max){
e = e || event;
max = max || 140;
var keycode = e.keyCode
  , len     = 0
  , This    = keyhandler
  , currlen = obj.value.length;

if (!('countfld' in This)){
    This.countfld = document.getElementById('letter-count');
}

if (keycode === 13) {
    //return document.forms[0].submit();
    return true;
}
if (currlen >= max) {
    This.countfld.innerHTML = '0';
    return false;
}
This.countfld.innerHTML = (max - obj.value.length);
return true;

}

And in the HTML file I used this:

<input type="text" onkeyup="return keyhandler(this,event,140)">

I hope it works for you! :D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top