views:

84

answers:

2

I have a form that looks kind of like this:

<div>
    <div class="contact">
        <h1>Person's name</h1>
        <!-- more stuff goes here -->
        <form method="post" action="myurl">
            <input type="submit" value="go" />
        </form>
    </div>
    <div class="contact">
        <h1>Another name</h1>
        <!-- more stuff goes here -->
        <form method="post" action="myOtherUrl">
            <input type="submit" value="go" />
        </form>
    </div>
</div>

I'm using jQuery to capture the form's submit event and need to get the index of the div containing the button that submitted it. Normally I'd use jQuery's index() function like so:

var i = $(this).parents('.contact').index(this);

Unfortunately, the this operator in this case refers to the form that is being submitted. I think there's probably something simple I'm missing, but my mind's drawing a blank on this one.

+4  A: 

Keep it simple:

var parent = $(this).closest('div.contact'); // get containing DIV
var i = $('div.contact').index(parent); // get index relative to the rest
Paolo Bergantino
I'll just quote myself: "I think there's probably something simple I'm missing..."Thanks.
swilliams
No sweat. I know what its like to be too close to a problem.
Paolo Bergantino
+1  A: 
var i = $(this).parents('.contact:first').prevAll('.contract').length
duckyflip