tags:

views:

21

answers:

1

Hi, I'm new to jQuery, coming from prototype. I'm trying to traverse within a form to do some validation before the form submits. There are multiple versions of the same form on the page, with css classes, but not individual IDs.

Here is how I would do it in Prototype:

$$(".validatedForm").each( function(form) {
    form.observe("submit", function(event) {
        var vForm = event.findElement("form");
        var vCheckbox = vForm.down(".validatedCheckbox");

        if (vCheckbox.checked)
           return true;

        alert("Please accept the Terms and Conditions first");
        event.stop();
        return false;
    }
}

The problem I'm having with jQuery is that I can't use the traversal methods on the 'event.target' element, because it is not extended as it would be with prototype - and if I surround it with a dollarsign, I get every form on the page!

+1  A: 

Here's the jQuery equivalent:

$(".validatedForm").submit(function(e) {
     var shouldSubmit = false;
     $(this).children(".validatedCheckbox").each(function() {
        if($(this).attr('checked')) {
           shouldSubmit = true;
           return; //return from closure.
        }
     });
     if(!shouldSubmit) {
         alert("Please accept the Terms and Conditions first");
         e.preventDefault();
     } 
});
Jacob Relkin
Isnt the `each` extraneous... simply calling $('.validatedForm').submit(function(event){...});` will iterate over all the forms adding the handler.
prodigitalson
@prodigitalson, Yeah. I forgot to flatten that out. Thanks!
Jacob Relkin
Thanks! This looks like it's pointing the right direction, however, you have vCheckbox in there on line 4 which is not set anywhere. What should I set it to?
Jon Packer
@Jon Packer, I updated it.
Jacob Relkin