TheYaXxE
TheYaXxE

Reputation: 4294

Show alert when focusout, only once

I'm having a little problem with my script below. I'm trying to create a script where you can write some text in an input field, and when you have typed some text, you will get an alert when focus-out. The alert should only show, if the input contain text.

But the problem is, that if you're trying to write some text, delete it and then focus-out of the input, the alert do not show next time, when you actually have written something and then focus-out.

Right now, the alert function always will "disappear" when focus out, no matter if you have written any thing or not.

I have tried to add a var already_alert_me_once = true before the alert, and then put everything inside an: if(already_alert_me_once == false), but that didn't do the trick.

I have also tried to change $('#title').focusout(function() with $('#title').one('focusout', function() which almost did the trick.

Here is my current script:

// When focus on title


 $('#title').focus(function () {
    // Check if empty
    if (!$(this).val()) {
        $('#title').one('focusout', function () {
            if ($(this).val()) {
                alert("YEP");
            }
        });
    }
});

..and Here's a Fiddle

So my question is; How to I do so the alert only appears when you have written something, and after that never again (unless you reload the page).

Hope you can understand what I mean.

Thanks - TheYaXxE

Upvotes: 3

Views: 4994

Answers (3)

Alex
Alex

Reputation: 10216

pretty much the easiest solution, no need for .one or focus events :)

$('#title').blur(function() {
    if( $(this).val() ) {
        alert('!!');
        $(this).unbind('blur');
    } 
});

http://jsfiddle.net/T7tFd/5/

Upvotes: 2

Chris Brickhouse
Chris Brickhouse

Reputation: 648

instead of putting the variable "already_alert_me_once" inside the function, make it a global variable. that way the scope will be maintained. you could also add an attribute to the #title that indicates that it has already been clicked, then check to see if that attribute exists before executing the code.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can unbind the focus using:

$('#title').unbind('focus');

Working Fiddle

Upvotes: 3

Related Questions