Person nam...">

How do I get the index of an element without 'this'?

I have a form that looks something like this:

<div>
    <div class="contact">
        <h1>Person 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 am using jQuery to write a form event submit

and need to get the index div

containing the button that submitted it. I would normally use the jQuery function index()

like this:

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

      

Unfortunately, the operator this

in this case refers to form

who is being sent. I think it might be something simple that I am missing, but my mind is drawing a blank on this.

0


a source to share


2 answers


Keep it simple:



var parent = $(this).closest('div.contact'); // get containing DIV
var i = $('div.contact').index(parent); // get index relative to the rest

      

+5


a source


var i = $(this).parents('.contact:first').prevAll('.contract').length

      



+1


a source







All Articles