0

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?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Ash
  • 239
  • 2
  • 9
  • 25

2 Answers2

1

Try changing

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

to

$('#'+i).bind('click', function () {
iJade
  • 23,144
  • 56
  • 154
  • 243
1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks much for ur response. I need ID to be passed to the parameter of the UpdateDeviceDetails(). The value of the ID should be like 0..1.. (i.e the value of i from the for loop). – Ash Sep 23 '13 at 11:00
  • @Ash all the methods in my answer will do that. – Rory McCrossan Sep 23 '13 at 11:02