Mano Johnbritto
Mano Johnbritto

Reputation: 308

How to create "change" event handlers dynamically?

I create dropdown dynamically.

Their ids are ddl1, ddl2, ddl3 and so on.

$('#ddl1').focus(function() {
    var previous = this.value;
}).change(function() {
    var index = $(this).find('selected').index();
    $('#ddl1').find('option:eq(' + index + ')').hide();
    $('#ddl2').find('option:eq(' + index + ')').hide();
});

$('#ddl2').focus(function() {
...

Creation of 7 dropdowns makes me to write 7 change event handlers.

How to implement dynamically create change event?

My dropdown append methods are:

var x=1;
var dropdown=('#ddl1').html();
$('#btnadd').click(function() {    
   $('#divname').append('<select id="ddl'+x+' > </select> <option>../option>');
   x++;    
});

Upvotes: 0

Views: 80

Answers (2)

kapantzak
kapantzak

Reputation: 11750

Give a common class to every dropdown and refer to that. Also, use .on() (event delegation) to catch dynamic created elements:

$(document).on('change', '.common-class', function() {
   //Your function
   var currentId = $(this).attr('id');
});

UPDATE

Add the same class every time you append a select element:

//...
$('#divname').append('<select id="ddl'+ x + '" class="common-class"><option>../option></select>');

SELECTED OPTION

In order to get the selected option:

$('#current-id').find('option:selected').index();

Upvotes: 4

Alex Kobzin
Alex Kobzin

Reputation: 69

Variant without delegated events to reduce resource usage:

var $dds = $('select');

$dds.each(function(index) {
    var $this = $(this);
    processDdChange($this);
});

function processDdChange($obj) {
    $obj.on('change', function(e) {
        var $this = $(this);
        alert($this.attr('id') + ' | ' + $this.find(':selected').val());
});
}

https://jsfiddle.net/tasmanangel/2p9mbs7h/

Upvotes: 1

Related Questions