jquery fun

As I get more and more into jQuery, I learn a few more things.  The latest and greatest of things is .each().  The original premise is this: I have an Ajax based form, one that degrades sort of gracefully, but it shows and hides information based on what is submitted.  I got to the point where the form submits nicely if all the right information is put in, but then when I popped open the form, it still had my previous values in it.  Now this is fine if there’s an error, where we can correct it, but this doesn’t work so well when we want to submit something new.  In regular old javascript, we would need the name of the form, or the name of the objects in the form, and either clear them out one by one, or if we have the form, loop over the elements and set the value of the form element to “”.  Fine fine.  Of course, I have jQuery.  So I did a little searching and I found two nifty things.  First there was a selector that looked like it might work “:input” which is meant to give back an array of all the input elements on the page: var allInputs = $(“:input”);  I tried a few different ideas, not really understanding what the selector did, but I ran across “.each” in my hunts.  I thought this was brilliant because I could get my array of elements and loop over them with each and three lines of code, I’m done.  Well, that was if I could figure out how to only deal with the one form I wanted…

My first incarnation of trials was this:  (I always throw alerts in to make sure we are functioning, whether or not it was correct)

$(“:input”).each(function() {
   alert(‘boo’);
     $(this).val(”);
    });

 And this did just as I expected, it looped over all 50 or so inputs on the page, including buttons, selects, checkboxes etc.  It might be useful in another situation but not this one.  So then I tried playing with the plain selector since I really didn’t understand the :input selector:

$(“#contactForm input”).each(function() {
   alert(‘boo’);
     $(this).val(”);
    });

This turned out better, it was only clearing out the values in the specified form.  The only problem was, it was also clearing out the submit button, which I wasn’t looking for.  I went ahead and added one more thing, a filter:

$(“#contactForm input[@type='text']“).each(function() {
     $(this).val(”);
    });

This worked beautifully.  Maybe another day I’ll play with the “:input” selector, but until then, I found my solution, and I’m quite happy with it.  Now I just have to get the rest of the project done.