tags:

views:

29

answers:

1

I'm creating an inline edit input['text'] snippet with jQuery.

the html will be like this :

<div id="inline">
    <span class="item">Color</span>
</div>

I got stuck in here (here is my code) :

$('.item').each(function(){
  $(this).click(function(){
  $(this).hide();
  $(this).parent().append(
   '<form method="post" action="" id="inline_form">'+ 
   '<input type="text" value="'+ $(this).html() +'"> <input type="Submit" value="update" />'+ 
   ' <a href="#" class="cancel">Cancel</a></form>'
  );
 });
 });

I want to bind a click event to class '.cancel' that I've appended above , so when I click cancel, it will remove the form '#inline_form' and show back '.item'

I tried this

$('.cancel').each(function(){
  $(this).click(function(){
  $(this).parent('#inline').find('.item').show();
        $(this).parent('#inline_form').remove();
 });
 });

But it didn't work. How do I select '.cancel' so I can put a click event on it ???

A: 

I modified your code slightly, and I think this has the desired effect:

$('.item').each(function(){
        $(this).click(function(){
                $(this).hide();
                $(this).parent().append(
                        '<form method="post" action="" id="inline_form">'+      
                        '<input type="text" value="'+ $(this).html() +'"> <input type="Submit" value="update" />'+ 
                        ' <a href="#" class="cancel">Cancel</a></form>'
                );

        $('.cancel').each(function(){
               $(this).click(function(){
               $('#inline').find('.item').show();
               $('#inline_form').remove();
               });
        });
        });
 });

The key point here would be that you have to assign the cancel function at the same time as you create the link, since the link doesn't exist before then.

Keep in mind too that making a parent() call using an id string is superfluous, as your ids must be unique. Only one element should ever have a given id, so there's no point in looking for $(something).parent('#id') when $('#id') will always work just as well.

zombat
"The key point here would be that you have to assign the cancel function at the same time as you create the link, since the link doesn't exist before then. "now that you mentioned it. thx a lot.
mdennisa