Reputation: 13
I'm trying to create a function which copies text from a specific list element into an input form. What I'm struggling with is that my function just copies all the text instead of the specific element. Does somebody have any advice how to indicate the list objects correctly (and dynamically)? Thx!
<!--Copy into Form Field-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Input field and list items-->
<input type="text" class="form-control" id="input2" placeholder="Input" size="200">
<li class="test" id="li1">test</li>
<li class="test" id="li2">brumbo</li>
<!--Function to Copy list items into input field-->
<script type="text/javascript">
$(function () {
$('.test').on('click', function () {
var text = $('#input2');
text.val(text.val() +','+ $('.test').text());
});
});
</script>
Output after clicking on e.g. test should be: ,test (instead of ,testbrumbo)
Upvotes: 1
Views: 50
Reputation: 18975
You need change $('.test').text()
to $(this).text()
for get current li as
$(function () {
$('.test').on('click', function () {
var text = $('#input2');
text.val(text.val() +','+ $(this).text());
});
});
<!--Copy into Form Field-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Input field and list items-->
<input type="text" class="form-control" id="input2" placeholder="Input" size="200">
<li class="test" id="li1">test</li>
<li class="test" id="li2">brumbo</li>
<!--Function to Copy list items into input field-->
<script type="text/javascript">
</script>
Upvotes: 2
Reputation: 96316
.text()
returns the combined text content of all elements in your collection, and $('.test')
has selected all elements with that class in your document.
You want $(this).text()
, to only get the text of the current element that you are currently handling the click
event for.
Upvotes: 0