简体   繁体   中英

Why the jQuery classes are not working for the HTML elements generated from AJAX response?

I'm using PHP, jQuery, Smarty, etc. for my website. I'm having a HTML form. In this form there is a select control and couple of calendar controls. Some classes are added to these controls to achieve some javascript functionality. When the form loads for the first time the classes applied to these controls work but when I append the same controls with the same classes applied to them, the javascript functionality doesn't work. Why this is happening and how to resolve this issue? For your reference I'm putting below the small snippets of codes: HTML Code:

<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_start_date[1]" id="rebate_start_date_1" value="{$data.rebate_start_date}">
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_expiry_date[1]" id="rebate_expiry_date_1" value="{$data.rebate_expiry_date}">
<select class="states" multiple="multiple" name="applicable_states[1]" id="applicable_states_1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>

The AJAX response from PHP file is as follows:

$rebate_no = $_POST['rebate_no'];
 $states = '';
      foreach ($state_list as $key => $value) {
        $states .= "<option value=".$value['id'].">".$value['state_name']."</option>";
      }
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_start_date[$rebate_no]' id='rebate_start_date_$rebate_no' value=''>
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_expiry_date[$rebate_no]' id='rebate_expiry_date_$rebate_no' value=''>
<select class='states' multiple='multiple' name='applicable_states[$reabate_no]' id='applicable_states_$reabate_no'>
                    $states    
                    </select>

The actual code is very large. I've put in only small and necessary part of my code. Would you please help me in this regard please? Thanks in advance. The jQUery AJAX function code is below:

$(function() {
  $(".add_new_rebate").on("click", function(event) {
    event.preventDefault();
    var manufacturer_id =  $("#company_id").val();

    /*if($.active > 0) { //or $.active      
      request_inprogress();
    } else {*/  
      var next_rebate_no = $('.rebate_block').length + 1;
      var rebate_no      = $('.rebate_block').length + 1;

    if ($('.rebate_block').length>0) { 
      rebate_no = rebate_no+1;
    }

      $('.add_new_rebate').attr('disabled','disabled');
    //}

    $.ajax({
      type: "POST",
      url: "add_rebate_by_product.php",
      data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},  
      beforeSend: function() { 
        $('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
      },
      success: function(data) {
        if(jQuery.trim(data)=="session_time_out") {
        window.location.href = site_url+'admin/login.php?timeout=1';                
        } else {
          $('.rebate_block').append(data);
          $('.add_new_rebate').removeAttr('disabled');
        }
        $('.load').remove();
      }
    });    
 });   
});

because jQuery parses only loaded DOM, it doesn't work with something, that was added to DOM after jQuery processed it. look at "on" function in jQuery API

You Have to add .on if jquery > 1.7

$('#parent-selector').on('click', 'child-selector', funcion(){})

Child selector is a selector that is just added. You need to add add event in this style for new elements added dynamically on the page Till jquery 1.7 you can you .live('click')

Like others have mentioned, when you have jquery handlers on present elements they work fine, but the new elements are not binded to those handlers and that's the reason we need to use the .on() method.

So for the newly created elements, we are going to attach a click event handler or any event for that matter as:

.states :

$(document).on('change','.states',function(){ 
  //on change of select 
});


.date_control :

$(document).on('click','.date_control',function(){ 
 //on click of input .date_control 
});

DEMO

I had this problem too, but I found the answer.

Just like I Can Has Kittenz said. You .on() function will do the trick.

On the jQuery website here

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Which means that if you are calling ajax code (event handlers that weren't there when the code was loaded) you need to bind it to an element that was there.

Here is an example:

$( "body" ).on( "click", "p", function() {
    alert( $( this ).text() );
});

You can see that on the link above too. There it shows how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM