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.

有帮助吗?

解决方案

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++;
});

其他提示

Use .on(), instead of .change().

.change only binds once. If an element is added it needs to be re-bound. .on does this automatically.

Also, since you have an ID, you don't need to specify "select" as part of your selector.

jQuery('#warehouse-' + count) will do.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top