Search code examples
javascriptformsonkeypress

OnKeyUp,OnKeyDown and onKeyPress


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!


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?