简体   繁体   中英

javascript event handling

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...

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
    }
}

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);

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.

Why would you not just change it to lowecase on the onblur event before it validates?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM