Home > Blockchain >  My append only work for 1 set of element jquery
My append only work for 1 set of element jquery

Time:09-12

My post's comments append only work for 1 post but i want this to be work on every post
enter image description here

  <body>
    <input type="text" id="postInt" /><button id="postBut">Post</button>
    <div id="postAppend"></div>
  </body>


 $("#postBut").click(function () {
        var postIntVal = $("#postInt").val();
        $("#postAppend").append(
          "<div id='postContainer'><p>"  
            postIntVal  
            "</p><input class='postCmntInt' /><button class='cmntBtn'>Comment</button><div class='postCmnts'></div>"
        );
        $(document).on("click", ".cmntBtn", function () {
          var postCmntInVal = $(".postCmntInt").val();
          $(".postCmntInt").after("<p>"   postCmntInVal   "</p>");
          $(".postCmntInt").val("");
        });
    
        $("#postInt").val("");
      });

CodePudding user response:

Without your html it's a bit hard to see. but I've changed to your jquery so it should work.

The below code is what i have changed.

$(document).on("click", ".cmntBtn", function() {
  var postCmntInVal = $(this).closest(".postContainer").find(".postCmntInt");
  postCmntInVal.after("<p>"   postCmntInVal.val()   "</p>");
  postCmntInVal.val("");
});

The problem is inside your $(document).on("click", ".cmntBtn" function. You don't specify the relate to the button that you click and the elements where it should do the work.

Demo

$("#postBut").click(function() {
  var postIntVal = $("#postInt").val();
  $("#postAppend").append(
    "<div class='postContainer'><p>"  
    postIntVal  
    "</p><input class='postCmntInt' /><button class='cmntBtn'>Comment</button><div class='postCmnts'></div>"
  );
  $("#postInt").val("");
});
$(document).on("click", ".cmntBtn", function() {
  var postCmntInVal = $(this).closest(".postContainer").find(".postCmntInt");
  postCmntInVal.after("<p>"   postCmntInVal.val()   "</p>");
  postCmntInVal.val("");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="postInt" /> <button id="postBut">post</button>
<div id="postAppend"></div>

  • Related