Reputation: 489
want to create a password field where I want to check for capsLock on/off on keystroke. Once a user enters a value in smallcase and try to another field want to validate the password value. Thus want to use onkeypress for every key pressed and then onblur at the end.
But the problem I am facing is every time onkeypress is checked onblur is also executed.
<input type="password" size=50 id='r5PswFld' name="name" value="" onkeypress="checkCapsLock(event)" onblur=chkPsw(this.id) >
can anyone help me how to attain this.
thanks in advance...
better if I am able to do this using only javascript/html/css I me no other technologies like jquery...
Upvotes: 1
Views: 141
Reputation: 30498
This event is getting fired because you in checking the other checkbox input, you are blurring focus away from the current control.
Attach the onblur at the start your checkCapsLock(event)
:
document.getElementById("r5PswFld").onblur = function(chkPsw(this.id)'){};
If you find yourself having to perform an action that will focus away, detach it:
document.getElementById("r5PswFld").onblur = function(){};
Next time you fire checkCapsLock
it will reacttach if you need to. You could then also remove the onblue
attribute completely from your code.
That said, be careful of any onblur
validation. If is obtrusive (like an alert
) then it could quickly get very frustrating for the user.
EDIT
In repose to the comment below, I thought I'd correct for the problem of other blur bindings. I'll use jQuery for preference.
The correct solution would look something like:
function MyBlurFunc(){
chkPsw(this.id);
}
To bind:
$("#r5PswFld").blur(MyBlurFunc);
To unbind
$("#r5PswFld").unbind('blur', MyBlurFunc);
Upvotes: 1
Reputation: 20210
No, the blur event won't be executed the same time a keyPress event is fired. I assume you have an alert()
statement within your checkCapsLock()
event handler, which causes the loss of focus.
Upvotes: 0
Reputation: 5782
Unfortunately, onblur will get called whenever focus is left from the field, meaning if you open some sort of message box informing the user of having capslock on, you're removing focus and thus trigger the onblur event.
An alternative might be to activate a flag which you assign to be true prior to opening a message box so that in the case in which you enter chkPsw, you can ignore it.
In other words:
var flgEventsOff = false;
function checkCapsLock(event) {
if (fieldValueIsUpper) {
flgEventsOff = true;
alert('Please turn off capslock!');
flgEventsOff = false;
}
}
function chkPsw(id) {
if(!flgEventsOff) {
// Validate password
}
}
Upvotes: 1
Reputation: 9286
Why would you not just change it to lowecase on the onblur event before it validates?
Upvotes: -1