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 someone help me in this?
-
my html code <input type="password" name="password" size=30 onkeyPress="checkPassword()" />Raja Roy– Raja Roy2011-09-27 11:07:28 +00:00Commented Sep 27, 2011 at 11:07
-
Edit your post and add checkPassword() function contents.antyrat– antyrat2011-09-27 11:14:04 +00:00Commented Sep 27, 2011 at 11:14
-
The function checkPassword() merely checks whether the password is of a specified length. The problem is that the function is getting called only once instead of everytime a character in entered.Raja Roy– Raja Roy2011-09-27 11:21:51 +00:00Commented Sep 27, 2011 at 11:21
Add a comment
|
4 Answers
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/>
Comments
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).
2 Comments
Raja Roy
In my case i am checking whether the password length is less than 8 characters. Thus when i insert for the first time it shows the appropriate message. However even when the length is more than 8 it keeps diplaying the message.
Atul Gupta
Then you are missing else statement..
if(length<8)alert('Less than 8'); else alert('clear field'); else statement is needed to clear message box