Show warning when focusing, only once

I have a little problem with my script below. I am trying to create a script where you can write text in an input field, and when you type some text, you will get a warning with focus. A warning should only show if the input contains text.

But the problem is that if you try to write some text, delete it and then focus on the input, the warning will not appear the next time you actually wrote something, and then focused.

At the moment, the warning function will always “disappear” when focusing, regardless of whether you wrote something or not.

I tried adding var already_alert_me_once = truebefore the warning and then putting everything inside :) if(already_alert_me_once == false, but that did not help.

I also tried changing $('#title').focusout(function()to $('#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 is the script

So my question is; How to do this, a warning appears only when you have one , and after that never again (unless you reload the page).

I hope you understand what I mean.

Thanks - TheYaXxE

+3
source share
3 answers

pretty much the easiest solution, not needed for .one or focus events :)

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

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

+2
source

You can untie focus using:

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

Working script

+3
source

instead of placing the variable "already_allet_me_once" inside the function, make it global. Thus, the volume will be saved. you can also add an attribute to #title, which indicates that it has already been pressed, and then check if this attribute exists before executing the code.

0
source

All Articles