mickormick
mickormick

Reputation: 253

jQuery Ajax - return value to specific DIV

Can one of you jQuery kings please tell me why my script.asp will not load for each separate button? I modified the code form http://www.sitepoint.com/ajax-jquery/. Thanks

<html>  
<head>  
<title>AJAX with jQuery Example</title>  
<script type="text/javascript" src="jquery.js"></script>  
</head>  
<body>  
<div id="wrapper">  

  <script type="text/javascript">  
    $(document).ready(function(){  
      $(".generate").click(function(){  
        $(this).find('div.quote').load("script.asp");  
      });  
    });  
  </script>

<input type="submit" id="generate1" class="generate" value="Generate!"><br />  
<div class="quote"></div><br><br>  

<input type="submit" id="generate2" class="generate" value="Generate!"><br />  
<div class="quote"></div><br><br>  

<input type="submit" id="generate3" class="generate" value="Generate!"><br />  
<div class="quote"></div>  

</div>  
</body>  
</html>  

Upvotes: 1

Views: 446

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

your .find( finds WITHIN the .generate class (enclosed in) .nextAll( finds all SIBLINGS with the selector applied :first being of course the first one of those selected siblings

$(".generate").click(function(){
   $(this).nextAll('div.quote:first').load("script.asp");
}); 

an alterative would be to wrap the input and the quote div in another div and then do:

<div class='quoteHolder'>
    <input type="button" id="generate1" class="generate" value="Generate!"><br /> 
    <div class="quote"></div>
</div>

$(".generate").click(function(){
       $(this).parent().find('div.quote').load("script.asp");   
});   

NOTE: in my example, I changed the input type to 'button' because, it is not really a submit now is it, an that will cause other interesting challenges.

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

You need to use nextAll and first to select the closest div.quote sibling:

$(".generate").click(function(){  
    $(this).nextAll('div.quote').first().load("script.asp");  
});  

.find finds all descendants of the selector matching the given selector, not siblings like you want.

Upvotes: 1

Blender
Blender

Reputation: 298562

.find() assumes there are elements nested inside of the element you're querying. Your element, however, is next to the element you're working with.

Try this:

$(this).next('.quote').load('script.asp'); 

Upvotes: 3

Related Questions