Reputation: 657
I have a set of number input fields, labeled small & medium, and a set of div's with the label small and medium. When you add a number to the small number input field a text input should insertAfter the div labeled small. When you subtract a number from the small number input field, the text input field that was recently added should be removed. the adding and removing of the text input should be the last one in the list.
when you remove a text field it should only remove the text field with the associated size.
Right now my script is adding text input fields at the top of the newly generated inputs (I know that it is happening this way because my script says to insertAfter the label, so it will always add a input at the top, but I don't want that).
Also right now it is removing the very last input that is present and not the very last input of the associated size.
It is easier to see what i am talking about when you fill in the inputs (a,b,c after adding them to see which one is being removed and where they are being added).
This is complicated for me to explain in words, but when you look at the fiddle, it may become more clear. if you need me to explain something else, please ask.
script:
$('.product-quantity').each(function() {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
ele = $(this).closest('[id^="product"]').find
('[data-size="'+this.name+'"]'),
inc = val >= old;
if (inc) {
$('<input/>', {'class': 'name-number-field'} ).insertAfter(ele);
}else {
$('.name-number-field', ele.parent()).first().remove();
}
$(this).data('val', this.value);
});
Upvotes: 2
Views: 174
Reputation: 318182
Something like this maybe
$('.product-quantity').each(function () {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
ele = $(this).closest('[id^="product"]').find('[data-size="' + this.name + '"]'),
inc = val >= old;
if (inc) {
$('<input/>', {
'class': 'name-number-field'
}).insertAfter(ele.nextUntil('div').last().length ? ele.nextUntil('div').last() : ele);
} else {
ele.nextUntil('div').last().remove();
}
$(this).data('val', this.value);
});
Upvotes: 1