Jade Han
Jade Han

Reputation: 1295

create function about buttons click, buttons created by loop

this image is my app post detail page this app is service about booksaling so user can post about booksale

enter image description here

the feature is

so i decide using js+ jquery

here's my js code

(function(){

$(document).ready(function(){
    //$book_list_num is received number of books
    //book1, book2, book3//$book_list_num = 3 
    $book_list_num = $("div").data("listNum");

    console.log($book_list_num);

    var $cancel_button = []

    for(i=1; i<= parseInt($book_list_num); i++){

        //$cancel_button[0]=#btn1,
        //$cancel_button[1]=#btn2,
        //$cancel_button[2]=#btn3
        $cancel_button[$cancel_button.length] = $("#btn"+i);


        $cancel_button[i].on('click', function(event){
           //test alert
           alert(i)
        });
    };
});

})();

but web browser console show error

cancelbutton.js:14 Uncaught TypeError: Cannot read property 'on' of undefined

I can not understand why js can't read onmethod please somebody help me

Upvotes: 1

Views: 88

Answers (2)

vijayP
vijayP

Reputation: 11502

Instead of trying adding click event listener in for loop can you please try following code:

$("[id^=btn]").on('click', function(event){
    var id = $(this).attr("id");
    var number = id.replace("btn", "");
    //test alert
    alert(number)
});

Here we are attaching click handler for all the DOM elements whose id starts with "btn". Hope it will help you a bit.

Upvotes: 1

cske
cske

Reputation: 2243

It comes from here:

$cancel_button[i].on('click', function(event){
   //test alert
   alert(i)
})

Change to:

for(var i=0,l = parseInt($book_list_num);i<l; i++){

    //$cancel_button[0]=#btn1,
    //$cancel_button[1]=#btn2,
    //$cancel_button[2]=#btn3
    $cancel_button[i] = $("#btn"+(i+1));


    $cancel_button[i].on('click', function(event){
       //test alert
       alert(i)
    });
};

Upvotes: 0

Related Questions