Reputation: 1263
I'm trying to create just 2 simple boxes and allowing uses to choose data from 1 box, which copies it to the second box. If there is already a same one on the second box, append some simple text behind.
It works basically when the item is not in the second box. However, when it is, I'm unable to append data to the text.
Here's a simple example.
https://jsfiddle.net/9mbgw20e/5/
<div id="inventory">
<div class='item'>
<span>Apple</span>
</div>
<div class='item'>
<span>Pear</span>
</div>
</div>
<hr>
<div id="selected">
</div>
// bring the items from inventory to selected
// if selected is found, add some text to the back of it
$('.item').on('click', function() {
var h = $(this)[0].outerHTML;
var found = false;
var foundId = '';
if ($('#selected').children().length < 1) {
// if there's nothing selected, just straight add this
return $('#selected').prepend(h);
}
$('#selected').children().each(function() {
if ($(this).find('span').text() == $(h).find('span').text()) { // if there is already one in selected div
console.log('Found duplicated.');
found = true;
foundId = $(this)[0].outerHTML;
}
});
if (!found) {
// if item is not in selected div, add
$('#selected').prepend(h);
} else {
// if item is in selected div, add some text to it
$(foundId).append('1, ');
}
});
Clicking the first time works, but after clicking it the second time, nothing happens.
Upvotes: 0
Views: 31
Reputation: 92501
Try using the first()
method instead:
foundId = $(this).first();
Upvotes: 0