Search code examples
javascriptjqueryjquery-load

Jquery - load() multiple times


I have the following code:

<div class="banner_large">
    <h4 class="titulo">Text</h4>
       <div class="block_text_banner">
           TEXT TEXT TEXT                
             <a href="javascript:void(0)"
             class="btn_interested btn btn-primary">I'm Interested</a>
        </div>
        <div class="form_interested"></div>
</div>


<div class="banner_large">
    <h4 class="titulo">Text</h4>
       <div class="block_text_banner">
           TEXT TEXT TEXT                
             <a href="javascript:void(0)"
             class="btn_interested btn btn-primary">I'm Interested</a>
        </div>
        <div class="form_interested"></div>
</div>


<div class="banner_large">
    <h4 class="titulo">Text</h4>
       <div class="block_text_banner">
           TEXT TEXT TEXT                
             <a href="javascript:void(0)"
             class="btn_interested btn btn-primary">I'm Interested</a>
        </div>
        <div class="form_interested"></div>
</div>   

Above are multiple banner ads

I want to load a form file, within the DIV form_interested only when the button btn_interested is clicked.

Notice: Each banner ad have a btn_interested button.

I tried this JQuery script but form loads on all banner ads:

<script>
 $(document).ready(function(){
    $( document ).on('click', ".btn_interested", function(){
      $('.form_interested').load('form_interested.html');
    });
 });
</script>

Solution

  • Change to classes, then isolate each instance within click handler:

    HTML

    <div class="banner_large">
        <h4 class="titulo">Text</h4>
           <div class="block_text_banner">
               TEXT TEXT TEXT                
                 <a href="javascript:void(0)" 
                 class="btn btn-primary btn_interested">I'm Interested</a>
            </div>
            <div class="form_interested"></div>
    </div>
    

    JS

    $( document ).on('click', ".btn_interested", function(){
       /* "this" is current button, look up to parent, then find element within parent to load*/
         $(this).closest('.banner_large').find('.form_interested').load('form_interested.html');
    });