There are several errors in your code, which stops you from calculating the sum
correctly:
-
#go
is not an input element, and therefore will never fire thechange
event. To observe change events on all your inputs, use$('#go input, #place')
instead. -
You are accessing the value of checked radio buttons and selected option incorrectly:
$('#go','#place').children(":selected")
This is incorrect, as (1) you are joining the selectors incorrectly, and (2) checkbox/radio buttons don’t have the
:selected
pseudo class. In order to retrieve the selected radio buttons and select option, you can perform this instead:- To access the checked radio button, use
$('#go input:checked')
- To access the selected option, use
$('#place option:selected')
- To access the checked radio button, use
See updated example based on your code:
$(document).ready(function() {
function validate() {
var sum = 0;
sum += +$('#go input:checked').data('price') || 0;
sum += +$('#place option:selected').data('price') || 0;
$('#result').html(sum === 0 ? '' : sum + '$');
}
validate();
$('#go input, #place').on('change', function() {
validate();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<div id=go>
<label><input type="radio" name="colorRadio" value="one" class="abc" data-price="1600">Live Band</label>
<label><input type="radio" name="colorRadio" value="two" class="abc" data-price="400">DJ</label>
<label><input type="radio" name="colorRadio" value="three" class="abc" data-price="500">Acoustic</label>
</div>
<div id="example" class="container">
<select id="place">
<option value="">pick</option>
<option value="a" data-price="100">a</option>
<option value="b" data-price="200">b</option>
<option value="c" data-price="300">c</option>
</select>
</div>
</form>
<div id="result" class="container"></div>