Reputation: 7303
I want to detect if this text field is empty or not and then run some code based on that.
Question is: how can I run the code only once ...and then run it once again each and every time that the state of the text field changes during one focus
empty
or not empty
.To further elaborate:
( The most important part in these jsfiddle's are shown in the console. )
Here is a jsfiddle of a code that executes the code every time you keyup (Not what I want. Just the initial code. ).
$('input').on("keyup", function() {
var val = $(this).attr('value'),
previous = $(this).prev();
if ( val === '' ) {
console.log('Empty');
}
else if ( val !== '' ) {
console.log('Text');
}
});
and Here is a jsfiddle of a code that executes the code once per focus (This is somewhat near to what I want).
What it is still missing, and what I can't seem to get done, is to basically run the code once again each and every time that the state changes during that one focus. How could I do that?
$('input').on("focus", function() {
$('input').one("keyup", function() {
var val = $(this).attr('value'),
previous = $(this).prev();
if ( val === '' ) {
console.log('Empty');
}
else if ( val !== '' ) {
console.log('Text');
}
});
});
Upvotes: 3
Views: 5038
Reputation: 14187
You need to use a plugin called jQuery Text Change from ZURB. Does everything you want and more, also has a trigger action called 'hastext' and 'notext', take a look at:
http://www.zurb.com/playground/jquery-text-change-custom-event
there are also demos there.
I made this for you (using that plugin).
LIVE DEMO:
http://jsfiddle.net/oscarj24/UtwNz/
Hope this helps :-)
Upvotes: 1
Reputation: 4762
You could keep a hold of the value of the field, and only trigger if the value's state has changed: http://jsfiddle.net/xk6A5/9/
Upvotes: 0