-1

I have a list of items that I can select but when I append additional items the new items are not able to be selected.

HTML

<ul id="list">
    <li attrit="AddInfo">item 1</li>
    <li attrit="MoreInfo">item 2</li>
</ul>
<button id="ud">update</button>

JQuery

$(document).ready(function() {
  $('#ud').click(function() {
    $.post("page", function(data){
      $('#list').append(data);
    });
  });
  $('#list ul').click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
  });
});

I am unable to select any of the items that are appended after the initial page is loaded.

What is the best way to address this?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
vip32
  • 77
  • 1
  • 10

1 Answers1

-2

Just redefine the action listener each time like this:

$(document).ready(function() {
  $('#ud').click(function() {
    $.post("page", function(data){
      $('#list').append(data);
      $('#list ul').click(function(){
        $(this).addClass("selected").siblings().removeClass("selected");
      });
    });
  });
  $('#list ul').click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
  });
});
James McDowell
  • 2,668
  • 1
  • 14
  • 27
  • If you downvote, please explain why. – James McDowell Sep 24 '15 at 15:46
  • [Dont Repeat Yourself](https://en.wikipedia.org/wiki/Don't_repeat_yourself) – Jamiec Sep 24 '15 at 15:47
  • I agree this might work but this is not a good way to write a program. Should create a generic binder function and call it whenever its needed. + jQuery is smart, sure, but your code could lead in a double event handler call for some elements. – Stranded Kid Sep 24 '15 at 15:54