StudioTime
StudioTime

Reputation: 23969

JQuery traverse up then down

I have the following structure:

<div>
    <button class="buttonClass">Click Me</button>
</div>
<div>
    <form id="formID">...</form>
</div>

When the form is submitted I want to simulate a click on the button with class buttonClass

This is what I'm trying but it's not finding the button and simulating the click:

$.ajax({
    type: "POST",
    url: URL,
    context:this,
    data: $(this).serialize(),
    success: function (data) {
        $(this).closest('.buttonClass').click(); // not finding button
    }
});

There are several forms and buttons on the page so I only want to click the nearest buttonClass

Upvotes: 0

Views: 93

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82231

I believe $(this) in current context is refering to form element. you can use:

$(this).parent().prev().find('.buttonClass').click();

Upvotes: 1

Popnoodles
Popnoodles

Reputation: 28409

Assuming $(this) is the form, since you're using $(this).serialize $(this).closest('.buttonClass').click() can't find the button because it's not an ancestor of the form, it's elsewhere.

You need an ancestor that contains both the form and the button to traverse to

<div class="wrapper">
    <div>
        <button class="buttonClass">Click Me</button>
    </div>
    <div>
        <form id="formID">...</form>
    </div>
</div>

then you can find it

$(this).closest('.wrapper').find('.buttonClass').click();

Upvotes: 1

Related Questions