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?

2

2 Answers 2

1

Try changing

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

to

$('#'+i).bind('click', function () {
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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 all the methods in my answer will do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.