Ash
Ash

Reputation: 237

Binding click events in a for loop

I am creating a unordered list and a button in the for loop. I want to bind a click function for the buttons in the same for loop.

Tried with the concatenating option. It`s not working.

function displayFeeds(items){
    var ul = $('#listview');
    for (var i = 0; i < items.length; i++) {
         var li = $('<li/>').html(items[i].DeviceNames);
         li.append($('<li/>').html(items[i].DeviceQuantity));
         li .append('<input type="button" value="Add" id="'+i+'">');
         // Enhance new button element
        li.append($('<hr>')); 
         ul.append(li); 


    $('#"+i+"').bind('click', function () {             
        console.log("called");
        var clickedID = this.id;
        console.log(clickedID);
        UpdateDeviceDetails(clickedID);             
    });
    }
}  

What should I do here?

Upvotes: 0

Views: 159

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Aside from the syntax error stopping your current code from working, appending x number of click handlers in a loop will be relatively slow. A better solution is to attach a delegate event to a single shared parent element. Try this:

function displayFeeds(items){
    var ul = $('#listview');
    for (var i = 0; i < items.length; i++) {
        var li = $('<li/>').html(items[i].DeviceNames);
        li.append($('<li/>').html(items[i].DeviceQuantity));
        li.append('<input type="button" value="Add" class="add-input" />');
        li.append($('<hr>')); 
        ul.append(li); 
    }
}

// single event handler...
$('#listview').on('click', '.add-input', function() {
    UpdateDeviceDetails(this.id);             
});

You could even simplify that by just passing the reference of UpdateDevideDetails to the click handler, something like this:

$('#listview').on('click', '.add-input', UpdateDeviceDetails);

var UpdateDeviceDetails = function(el) {
    var id = el.id;
    // rest of your logic...
}

Also note that the HTML generated by your jQuery will be invalid - you cannot have an li as a direct child of another li element. All li elements should have a parent ul or ol.

Upvotes: 1

iJade
iJade

Reputation: 23791

Try changing

$('#"+i+"').bind('click', function () {

to

$('#'+i).bind('click', function () {

Upvotes: 1

Related Questions