2

I am trying to create functionality in a form very similar to what is described in this question. I want to mark the inputs in a form that are incomplete by dynamically adding (or removing) a class. However, in that question, this only updated on blur. I want the class to be added when the page loads. I currently have:

$(document).ready(function() {
    $('.eval-form input').blur(function() {
        if( !$(this).val() ) {
            $(this).parent().addClass('incomplete-answer');
        }
        else {
            $(this).parent().removeClass('incomplete-answer');
        }
    });
});

I want to replace .blur with some method that will proceed to the function when the page loads for the first time. It seems like this should be a simple thing I am trying to do, but my lack of familiarity with jQuery is kicking me and I haven't had any luck with the documentation.

Community
  • 1
  • 1
Julia Ebert
  • 1,583
  • 1
  • 21
  • 39

2 Answers2

1

You can trigger the event. The handler will be called once for each element in the collection.

$('.eval-form input').blur(function() {
  // ...
}).blur();

You can also minify your code by using the toggleClass method:

$(document).ready(function() {
    $('.eval-form input').blur(function() {
        $(this).parent()
               .toggleClass('incomplete-answer', $.trim(this.value) === '');
    }).blur(); // trigger the event once on DOM ready
});
Ram
  • 143,282
  • 16
  • 168
  • 197
  • This would totally work, and has the added benefit of maintaining the attachment to the input – Ben Potter Aug 06 '14 at 21:08
  • Thanks! Is there a way that I can also use that same function to call whenever a field is blurred? Obviously, I could write that original code in there again, but is there a way to reuse the code? – Julia Ebert Aug 06 '14 at 21:09
  • @Pterosaur Well, there is no need to define another handler. You should just call the handler once on DOM ready. The second snippet in the answer is all you need to do. – Ram Aug 06 '14 at 21:17
0

Sure, piece of cake! What you want is a each loop on the inputs:

$(document).ready(function() {
    $.each($(".eval-form input"), function(i, e) {
        if(!$(e).val()) {
            $(e).parent().addClass('incomplete-answer');
        } else {
            $(e).parent().removeClass('incomplete-answer');
        }  
    });
})
Ben Potter
  • 321
  • 1
  • 4
  • What does the `i` do in this function? – Julia Ebert Aug 06 '14 at 21:11
  • i is the index of the element in the loop. Basically, you're iterating over an array, and its giving the callback function two values: the position in the array, and the element you're currently looking at. – Ben Potter Aug 06 '14 at 21:13
  • Note that you are iterating through `".eval-form input"` string. `$.each` doesn't accept a selector. It's an utility function. Either pass `$(".eval-form input")` to it or use the `$().each()` method. – Ram Aug 06 '14 at 21:21