I have the following html for 2 select dropdowns:
<select name="options[4614]" id="select_4614" title="" data-selector="options[4614]" aria-required="true">
<option value="">-- Please Select --</option>
<option value="18923" money="100">Option 1</option>
<option value="18924" money="200">Option 2</option>
</select>
<select name="options[2433]" id="select_2433" title="" data-selector="options[2433]" aria-required="true">
<option value="">-- Please Select --</option>
<option value="9353" money="0">Option A</option>
<option value="9351" money="100">Option B</option>
<option value="9352" money="200">Option C</option>
</select>
I am trying to add together the values in the attribute 'money' for each selected option and then output this is another div.
I am using the below as a guide:
$(function () {
var fields = $('.product-custom-option.admin__control-select').change(calculate);
function calculate() {
var pricesum = 0;
fields.each(function () {
pricesum = $(this).val();
})
$('.outputdiv').html(pricesum.toFixed(2));
}
})
Which adds the option values together, but when changing .val to .attr('money') it returns NaN (not a number).
Any guidance on what is going wrong would be most appreciated.
Thank you.
CodePudding user response:
Change your calculate function as below (commented for better understanding):
$(function() {
var fields = $('.product-custom-option.admin__control-select').change(calculate);
function calculate() {
var pricesum = 0;
fields.each(function() {
//this refers to select elements not options in this context
//get selected option
let money = $(this.selectedOptions[0]).attr("money");
//skip not selected values
if (Number(money)===money) pricesum = money;
})
//console.log(pricesum)
$('.outputdiv').html(pricesum.toFixed(2));
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="options[4614]" id="select_4614" title="" data-selector="options[4614]" aria-required="true">
<option value="">-- Please Select --</option>
<option value="18923" money="100">Option 1</option>
<option value="18924" money="200">Option 2</option>
</select>
<select name="options[2433]" id="select_2433" title="" data-selector="options[2433]" aria-required="true">
<option value="">-- Please Select --</option>
<option value="9353" money="0">Option A</option>
<option value="9351" money="100">Option B</option>
<option value="9352" money="200">Option C</option>
</select>
<div ></div>