22

When a user creates a new account on my website I want to check if the name already exists. I want this check to run when they leave the username input box and go to enter a password.

I tried :

<input type="text" onkeyup="check_user(this.value)"/>
Tony
  • 9,672
  • 3
  • 47
  • 75
mamrezo
  • 2,273
  • 5
  • 19
  • 23
  • no this is for register that if this user exist cannot submit whit this username. – mamrezo Feb 03 '11 at 12:31
  • What you are looking for is the `blur` event. But @Awais provided an even better solution, as the `change` event will be raised, when the input looses focus, but only if the text changed. – Felix Kling Feb 03 '11 at 12:41
  • possible duplicate of [Detect changed input text box](http://stackoverflow.com/questions/6153047/detect-changed-input-text-box) – azerafati Oct 30 '14 at 17:19

5 Answers5

23

Call the function on the change event of text field:

<input name="username" onChange="check_user(this.value);" type="text"/>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
14

You need to use the "onblur" event. It fires when a control loses its focus, which seems to be exactly what you need.

13

Because you used onkeyup in your code example, it sounds like you are looking to call a function on every keystroke. If that is the case, then instead of onchange - which fires when the input loses focus - you should use oninput which will fire anytime there is a change inside of input.

Ben
  • 5,085
  • 9
  • 39
  • 58
1

I think you are looking for check the duplication of user. you have to write server side code for that.

enthusiastic
  • 732
  • 2
  • 9
  • 18
0

If you want to fire when something specific is type into the window:

phr = 'lol'
ltr = phr.split('')
text = ''

document.addEventListener('keyup',function(k){
    if (ltr.includes(k.key)) {
        text += k.key
        if (text == phr) {
            console.log('Typed!')
            text = ''
        }
    } else {
        text = ''
    }})

As a function your can use it like:

function wtt(phrase,clb) {
    phr = phrase
    ltr = phr.split('')
    text = ''

    document.addEventListener('keyup',function(k){
        if (ltr.includes(k.key)) {
            text += k.key
            if (text == phr) {
                clb()
                text = ''
            }
        } else {
            text = ''
        }})
}

wtt('my phrase', function () {
    console.log('dostuff')
})
Blaze612 YT
  • 594
  • 7
  • 13