Jon Packer
Jon Packer

Reputation: 123

Traversing within single elements with jQuery

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!

Upvotes: 0

Views: 46

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163318

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

Upvotes: 1

Related Questions