0

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
    );
});
4
  • isn't timer undefined here or you are declaring it somewhere else?! Commented Jan 13, 2014 at 10:25
  • @A.Wolff timer is defined on line 3 above, so it's scope is in the function. Commented Jan 13, 2014 at 10:25
  • 1
    @JeremyMiller No, it is not! BTW, this is not valid syntax, using var Commented Jan 13, 2014 at 10:26
  • @A.Wolff Spot on! Good catch... can't believe I didn't see that! Commented Jan 13, 2014 at 10:30

1 Answer 1

3

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
    );
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi. Thank you. I have tried this, but its giving an error of 'TypeError: f.nodeName is undefined' in the jquery library. Any ideas?
Your FIELD as a name attribute? What about providing relevant HTML code and a jsfiddle?!
Fixed it myself. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.