Search code examples
jqueryappendthis

how to append text to its own div container without appending it to the other div container?


what the jquery code does below is it only clears the textbox

$(document).ready(function(){
   var someText = $(".someText");
   
   $(".add").on("click", function(){
      $(".container", this).append(someText.val());
      $(someText).val("");
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
   <div class="add">+</div>
   <input class="someText" type="text">
</div>
     
<div class="container">
   <div class="add">+</div>
   <input class="someText" type="text">
</div>

how do I append the text to its own container without being appended to the other?


Solution

  • Your selectors are a bit broken – presumably you want each + to only append the value of its associated .someText. Is this what you had in mind?

    $(document).ready(function(){
       $(".add").on("click", function(e){
          var container = $(this).closest(".container");
          var someText = $(".someText", container);
    
          container.append(someText.val());
          someText.val("");
       });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
       <div class="add">+</div>
       <input class="someText" type="text">
    </div>
         
    <div class="container">
       <div class="add">+</div>
       <input class="someText" type="text">
    </div>