Reputation: 1295
this image is my app post detail
page
this app is service about booksaling so user can post about booksale
the feature is
userA
create a post (he want sale book1, book2, book3)userA
should click sold out button
sold out button
clicked, sold out
will converted click cancel
and strike
line will added book2 (like 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 on
method
please somebody help me
Upvotes: 1
Views: 88
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
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