Search code examples
jqueryjquery-post

jQuery .add() and empty()


<div id="msg_container">
  <span> Is this helpful ? </span>
  <span class="feedback"> 
     <a title="like"> Yes </a> 
     <a title="dislike"> No </a> 
  </span>
</div>

// jQuery Script
$('.feedback a').live('click', function() {
   var reference = $(this).parent().parent();
   $.post("URL", $("FORM").serialize(),
        function(data){
    // posted successfully and following will be executed
    reference.empty();
            reference.add('<span> You have given feedback </span>');

   }, "json");       
});

The process would be:

  1. User will be asked 'Is this helpful? Yes No'
  2. Upon clicking either 'Yes' or 'No', .post method will be executed
  3. After posting to server successfully,
  4. I want the DOM element id="msg_container" to change entire content to a normal span or paragraph with the sentence 'You have given your feedback' so that each user can only give one feedback.

The problem:

  1. Once the div "msg_container" it's emptied, the .add() didn't work.
  2. Even without emptying the "msg_container', the .add() still didn't work.
  3. I read the documentation, the .add() doesn't seem to work with reference object just like I did above.
  4. I have to assign the reference to variable as such var reference = $(this).parent(); Otherwise, after executing $.post, the $(this) will lose its original 'this' reference.

Any idea how to solve this? I can accept alternative solutions as long as my requirement is fulfilled.


Solution

  • You could use append()

    reference.append('<span> You have given feedback </span>');