开发者

Calling a javascript function everytime a key is pressed in input field

I want to call a function whenever a key is pressed. I am using onKeyPress event handler. However i see that it calling the function only the first time the key is pressed. I want to call it everytime a key is pressed. Can som开发者_JAVA技巧eone help me in this?


Probably a bit too late but...

<script>
    function checkPassword(pwd){
      if(pwd.length < 8){
        document.getElementById('message').innerHTML = 'Password needs to 8 characters minimum.';
      }
      else{
        document.getElementById('message').innerHTML = '';
      }
    }
  </script>

In the HTML body...

  <input type="password" name="password" size=30 onkeyup="checkPassword(this.value)" />
  <span id="message"></span><br/>


Answer 1.

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
    var jq=jQuery.noConflict();
    jq(document).ready( function(){
        jq(document).keydown(function(event){
            // -- here comes your code of function --
            jq("#keycode").html(event.which); // example code, event.which captures key index
        });
    });
</script>
</head>
<body>
    <div id="keycode">Press any Key to see its index</div>
</body>

Answer 2.

You should replace onKeyPress with onchange | http://www.w3schools.com/jsref/event_onchange.asp


I ran your HTML code and it works as expected.

Your checkPassword() function may be set to do something only if the password is of a specified length, as in this code:

<input type="password" name="password" size=30 onkeyPress="checkPassword(this)" />
<script type="text/javascript">
function checkPassword(pass) {
    if (pass.value.length > 7) {
        alert("Password is greater than 7 characters.");
    } else {
        //DO NOTHING
    }
}
</script>

In this case, if the password isn't greater than 7 characters, the function may seem like it isn't getting called, but it actually is (the function just runs so fast you don't even know that it's getting called).


<script>
function l(ths){
    document.getElementById('length').innerHTML=ths.length;
}
</script>
Length: <span id="length"></span><br/>
<input type="text" onkeyup="l(this.value);"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜