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?
4
Answers
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?You want to use
$(this)
– your current selector is trying to find a container insidethis
but the container is the parent so you need to traverse up the tree, not down it.Below I have switched out to use the event and it’s current target
e.currentTarget
instead ofthis
Use
closest(".container")
to select a parent container (and not any of its siblings), see https://api.jquery.com/closest/#closest-selectorAlso, to get the input text, make sure to select only the
<input>
next to the "+" control by usingsiblings()
, see https://api.jquery.com/siblings/#siblings-selectorYou should use jQuery function .closest() to get the parent and then find the input text placed inside this parent. Like this, you will get only the target input and not all.
Try this code :