-2

My JQuery Code is:

$(document).ready(function() {  
  $('#btnGenSpan').on('click', function(e) {
    $("#div_container").html($("#div_container").html()+
            "<span>Item-01 <a href='?delete=1' class='delete_item'>X</a></span><br />");
  });

  $('a.delete_item').on('click',function(e) {
    alert('delete clicked');
    return false;
  });
});

Here is html content:

<input type="button" id="btnGenSpan" value="Generate More Item" /><br /><br />
<div id="div_container">
  <span>Default Item-01 <a href='?delete=111' class='delete_item'>X</a></span><br />
  <span>Default Item-02 <a href='?delete=112' class='delete_item'>X</a></span><br />
</div>

Here is the JSFiddle here

For static items(Default Item-01 & Default Item-02) X anchor works fine and called delete_item but for those span which are generated by jquery(same html class & anchor generated as default) not called. any help is highly appreciated.

PSL
  • 123,204
  • 21
  • 253
  • 243
user1911703
  • 740
  • 5
  • 8
  • 24
  • Not much point in passing `(e)` if you're not using it. – TheCarver Dec 21 '13 at 03:29
  • 2
    don't you look at answers to your questions? gave you this answer 3 hours ago http://stackoverflow.com/questions/20714059/how-to-delete-jquery-autocomplete-item – charlietfl Dec 21 '13 at 03:57
  • 1
    @charlietfl oops... noticed 22 question with not a single accepted answer... :/ – PSL Dec 21 '13 at 04:02

2 Answers2

3

You may want to try using event delegation syntax of on to have the event available for the dynamically created elements. Reason being your original event is bound only to the a.delete_item that already existed in DOM at the time of event binding, so newly added ones just did n't have that event bound to it. So bind the event to the parent container that exists in DOM as long as you need the event so that it gets delegated to the selector (jquery uses event bubbling to make this work) when that event happens.

  $('#div_container').on('click','a.delete_item', function(e) {
      e.preventDefault();
      alert('delete clicked');
  });

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243
0

You must creat event for new DOM Try this

$(document).ready(function() {  
  $('#btnGenSpan').on('click', function(e) {
    $("#div_container").html($("#div_container").html()+"<span>Item-01 <a href='?delete=1' class='delete_item'>X</a</span><br />");
      $('a.delete_item').on('click',function(e) {
        alert('delete clicked');
        return false;
      });
  });

  $('a.delete_item').on('click',function(e) {
    alert('delete clicked');
    return false;
  });
});
HDT
  • 2,017
  • 20
  • 32