Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery replaceWith only work once?

Tags:

html

jquery

I have some jQuery code that replaces data in a div each time the form is submitted. For some reason the replaceWith function is only replacing the div once? Can anyone tell me what am I missing?

HTML

<div class="count"></div>

jQuery

$(document).ready(function(){
  $("#like_unlike").submit( function(e) { //Second Form
    e.preventDefault();
    var url = "update_likes.php"; //Grab URL from form
    var formdata = $(this).serialize();
    console.log(formdata);   
    $.post(url, formdata, function(response) {
      //Post the form
      $('.count').replaceWith(response);
    });
  });
}); 
like image 203
JulianJ Avatar asked Dec 23 '22 22:12

JulianJ


1 Answers

replaceWith() doesn't "replace data in a div" - it actually replaces the element, meaning you won't be able to select it anymore because .count will be gone after your code executes.

Instead, replace the inner HTML of .count with html(), which would look like:

$('.count').html(response);
like image 94
Jon Uleis Avatar answered Dec 31 '22 14:12

Jon Uleis