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
);
});