jQuery: Select parent div of form that submitted with AJAX

Using jQuery, how can I select the parent div of the form that was submitted?

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
 $(document).on('submit', 'form', function() {
  $(this).parents('div').css('border','2px solid blue');
  $.post($(this).attr('action'), $(this).find(':input').serialize() , function(data) {
   $(this).parents('div').css('border','2px solid red');
  });
  return false;
 });
});

</script>
</head>
<body>

<div>
 <form action="./">
  <input type="submit" value="Submit" />
 </form>
</div>
<div>
 <form action="./">
  <input type="submit" value="Submit" />
 </form>
</div>
<div>
 <form action="./">
  <input type="submit" value="Submit" />
 </form>
</div>

</body>
</html>

Open in new window

LVL 10
skijAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
There are a number of ways of doing it.

If the <div> is an immediate parent of the form

$('form').parent();

Open in new window


if there are intervening elements between form and parent div then you would use

$('form').closest('div');

Open in new window


In your case I would go with .closest()
skijAuthor Commented:
The problem is that I need to specifically target the parent div of the form that was submitted.  There are multiple forms.  The code you posted would target the parent div of ALL the forms.

My question is how can I target the parent div of the form which was submitted?
Julian HansenCommented:
Exactly so you do it like this - bind to the submit event and then use the $(this) to find the closest div to the form that triggered the submit.

$('form').submit(function() {
   var parent = $(this).closest('div');
});

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

skijAuthor Commented:
Please test the code I posted in my question.  
I am already doing as you suggested:
$(this).parents('div').css('border','2px solid blue');

However the problem is that when the result is returned using AJAX it does not know which form the response is related to.  

In the example I posted, the div of the submitted form should get a red border after its results have been returned.
Julian HansenCommented:
Some things to understand about jQuery and asynchronous calls.

When you your code does the .post() the latter takes a lambda (the complete call back) that is then relative to the post - so when you use $(this) inside the complete function - it is no longer referring to the form but the $.post()

You need to save the parent in a variable and then use that variable inside the function like this
$(document).ready(function () {
 $(document).on('submit', 'form', function() {
  // SAVE THE PARENT AND CHAIN THE SELECTION TO THE .css() TO SET THE BLUE BORDER
  var parent = $(this).closest('div')
                      .css('border','2px solid blue');

  $.post($(this).attr('action'), $(this).find(':input').serialize() , function(data) {
    // USE THE SAVED parent IN THE COMPLETE
    parent.css('border','2px solid red');
  });
  return false;
 });
});

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
skijAuthor Commented:
Thanks.  Is there a chance that saving the variable this way could cause a race condition?
Julian HansenCommented:
How so?
Julian HansenCommented:
What I means is - what would be competing for it?
skijAuthor Commented:
var parent is being defined multiple times.  So if I submit all three forms the same second, and the form takes between 10 and 30 seconds to process, if the middle form is processed first would "var parent" being defined again cause a race condition?
Julian HansenCommented:
No there is no race condition.

Take a look at this sample. The form is a re-hash of your code - 3 buttons each linked to a different backend script. Each script takes a different time to load (instant, 5s, 10s). The sample demonstrates how each form is updated correctly as its AJAX finishes.

Source files are attached.
t1058-dist.html
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.