Chao  LI
Chao LI

Reputation: 99

Why Javascript is not working under appending?

I have a table in my html and I used append to attach all rows in the table using jquery. Part of the append section is shown below. I have an input section to change numbers but now this input click is not working anymore.

I wonder why? If I move the code back to my html table, it works. Also, the delete button is not working as well. I suspect this is to do with append feature?

$('.bundle-main').append('<li class="td td-amount">\
       <div class="amount-wrapper ">\
          <div class="item-amount ">\
             <div class="sl">\
               <input class="min am-btn" name="" type="button" value="-" />\
               <input class="text_box" name="" type="text" value="3" style="width:30px;" />\
               <input class="add am-btn" name="" type="button" value="+" />\
              </div>\
              </div>\
              </div>\
              </li>');

PS: The reason I want to use append is because I want to dynamically control my content and my css is working fine.

Do you know why?

Upvotes: 0

Views: 70

Answers (2)

Codemole
Codemole

Reputation: 3189

Because your event handler is defined before input is appended. You have 2 choices:

No1. After append input, then defined the event handler.

No2. Just use .on('click') on the wrapper like following:

$('.bundle-main').on('click', '.add.am-btn', function(){
  // To Do
}); 

Upvotes: 2

Pabs123
Pabs123

Reputation: 3435

Since you're appending the inputs dynamically, you need to make sure that the click listeners are added after the append. Otherwise they will not be present in the DOM and the click listener will not be attached.

Just attach your listeners after the append call.

Upvotes: 1

Related Questions