Search code examples
jquerydynamic-data

Cant call event on dynamically created elements using jQuery


I am creating a Row of elements where in my ROW i have a select box/Drop Down. What i want is that i want to call onChange function on every Drop Down on Every row.

count = 1;
jQuery('select[id="warehouse-' + count + '"]').change(function() {
    alert('hello');
    var urlWareHouse = "<?php echo $this->url('stock', array('action' => 'populateLocationInWarehouse', 'controller' => 'Stock')) ?>";
    url = urlWareHouse + '/' + jQuery('id="warehouse-' + count + '"]').val();
    SelectBoxNullValue = "Select Location";
    populateSelectBox(url, 'warehouse-'+count, 'location');
    count++;
});

My populateSelectBox function is simply an ajax call that populates data to newly created Select Element. I dont know what i am doing wrong. The thing is i cannot trigger onChange on newly created with my Approach.


Solution

  • Use the on() function to bind to elements even new ones, otherwsie you have to continuously rebind the element.

    jQuery(document).on("change",'select[id="warehouse-' + count + '"]',function() {
        alert('hello');
        var urlWareHouse = "<?php echo $this->url('stock', array('action' => 'populateLocationInWarehouse', 'controller' => 'Stock')) ?>";
        url = urlWareHouse + '/' + jQuery('id="warehouse-' + count + '"]').val();
        SelectBoxNullValue = "Select Location";
        populateSelectBox(url, 'warehouse-'+count, 'location');
        count++;
    });