I would like to add the products and total them. 99.99 should be added to the total amount.
what options are there?
$(document).ready(function() {
$('#btn-add').click(function() {
$('#select-from option:selected').each(function() {
$('#select-to').append("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
$("input[name='class']").val((parseFloat($(this).val()) + parseFloat($("input[name='class']").val())).toFixed(2));
});
});
$('#btn-remove').click(function() {
$('#select-to option:selected').each(function() {
$('#select-from').append("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
$(this).remove();
$("input[name='class']").val(parseFloat($("input[name='class']").val() - parseFloat($(this).val())).toFixed(2));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectfrom" id="select-from" multiple="" size="5">
<option value="0.00">--</option>
<option value="22.99">Product S</option>
<option value="27.99">Product S Boost</option>
<option value="32.99">Product S Boost</option>
<option value="37.99">Product M</option>
<option value="42.99">Product M Boost</option>
<option value="47.99">Product L</option>
<option value="62.99">Product XL</option>
</select>
<a href="JavaScript:void(0);" id="btn-add">Add »</a>
<a href="JavaScript:void(0);" id="btn-remove">« Remove</a>
<select name="selectto" id="select-to" multiple="" size="5"></select>
<input type="text" name="class" value="0">
<div type="text" id="classx">Here the total number including €99.99 should be calculated</div>
3
Answers
If I’ve understood what you’re asking, you want to add
99
to the summed value. As such, you could simply perform this mathematical operation on the sum before you update theinput
.However, there’s a few things you can do to make the code more succinct and take advantage of jQuery.
Firstly, you don’t need to add the
option
elements back in toselect-from
when removing items. This duplicates them.Secondly, you can just
clone()
elements instead of hacking together HTML strings and appending that content. This avoids the need for the expliciteach()
loop.Lastly, you can use
reduce()
to sum the selected options and update theinput
once, outside of the loop.Here’s a working example with the above changes, and DRY’d up slightly:
Also, as an aside, note that you’re using a very old version of jQuery. The latest version at the time of this question is v3.7.1. I would strongly suggest you update.
DRYed up further