Ahmed Bahieddine
Ahmed Bahieddine

Reputation: 13

How to edit in new generated code using jQuery?

I am working on my own project and i have a little problem with a new dynamically generating node it's not clicked here is the code sample:

HTML:

<ul id="container-comments">
    <li>
        <a href="#" class="comment-avatar" title="imax9">
           <img src="images/avatar.png" alt="imax9" />
        </a>
        <div class="content-box comment__body">
           <div class="comment__header">
              <a href="/user/imax9" class="comment__username">imax9</a>
              <div class="comment__meta">
                <span>8 hours ago</span>
              </div>
              <div class="edit" title="Edit">
                edit
              </div>
           </div>

          <div class="comment__content">
             <p>wonderful! Good luck with sales!</p>
          </div>
        <div class="comment__inline-edit"></div>

     </div>
   </li>

  </ul>

jQuery:

$('#comment-submit input[type=submit]').click(function (e) {
        e.preventDefault();
        updateComments(params); //this function updates the ul by adding
                                //new li contains the same html structure 
});

//it doesn't work for the new generated one
$('.edit').on('click', function () {
        var index = $('.edit').index(this);
        var commentEdit = $('.comment__content p').eq(index).text();
        $('.comment__content').eq(index).html('<textarea style="width: 500px; height: 50px; padding: 0px; resize: none;">' + commentEdit + '</textarea>');
        //then it supposed when i press enter key the edit is done
});

thanks so much

Upvotes: 1

Views: 70

Answers (3)

caramba
caramba

Reputation: 22490

try:

$(document).ready(function(){
    $(document).on('click','.edit',function(){
       // your function
    });
});

Upvotes: 1

Fazle Rabbi
Fazle Rabbi

Reputation: 902

Use delegation:

$('#container-comments').undelegate('.edit', 'click').delegate('.edit', 'click', function() {
     ...
     ...
}

Upvotes: 0

Spokey
Spokey

Reputation: 10994

You are not using .on() the right way in order for it to work on dynamic elements.

Try this.

$('#container-comments').on('click', '.edit', function () {
        var index = $('.edit').index(this);
        var commentEdit = $('.comment__content p').eq(index).text();
        $('.comment__content').eq(index).html('<textarea style="width: 500px; height: 50px; padding: 0px; resize: none;">' + commentEdit + '</textarea>');
        //then it supposed when i press enter key the edit is done
});

The structure is like

$('static selector').on('event', 'dynamic selector', function(){...});

Other wise it will work like a normal click

Upvotes: 2

Related Questions