Each time a field that has the class of 'required' is changed I want to set a timeout. My original script had a bug where if you move onto another field with the same class before the timeout is complete it resets it and only carrys out the function on the last field. To combat this, I want to add the name of the specific field to the timer function. However my attempt below doesn't work. I am thinking if there is a timer for each field it should work. Firstly, is my method correct? and if so what am I doing wrong? If not, how can I achieve my goal?
$('.required', this).bind('keyup change',function() {
var fieldName = $(this).attr('name');
var timer[fieldName] = null;
clearTimeout(timer[fieldName]);
timer[fieldName] = setTimeout(
function() {
if( !$(this).val() ) {
$(this).nextAll('.required-prompt').first().remove();
$(this).after(prompt);
} else {
$(this).nextAll('.required-prompt').first().remove();
required = true;
}
}
, 2000
);
});
-
isn't timer undefined here or you are declaring it somewhere else?!A. Wolff– A. Wolff2014年01月13日 10:25:18 +00:00Commented Jan 13, 2014 at 10:25
-
@A.Wolff timer is defined on line 3 above, so it's scope is in the function.user1932079– user19320792014年01月13日 10:25:47 +00:00Commented Jan 13, 2014 at 10:25
-
1@JeremyMiller No, it is not! BTW, this is not valid syntax, using varA. Wolff– A. Wolff2014年01月13日 10:26:11 +00:00Commented Jan 13, 2014 at 10:26
-
@A.Wolff Spot on! Good catch... can't believe I didn't see that!user1932079– user19320792014年01月13日 10:30:00 +00:00Commented Jan 13, 2014 at 10:30
1 Answer 1
Code should be like this:
var timer = {};
$('.required', this).bind('keyup change',function() {
var fieldName = $(this).attr('name');
clearTimeout(timer[fieldName]);
timer[fieldName] = setTimeout(
function() {
if( !$(this).val() ) {
$(this).nextAll('.required-prompt').first().remove();
$(this).after(prompt);
} else {
$(this).nextAll('.required-prompt').first().remove();
required = true;
}
}
, 2000
);
});