Некорректно работает переключение радиобаттонов
Считаем сумму значений выбранных радиокнопок. При повторном нажатии на радиокнопку нужно убирать атрибут "checked" и пересчитывать сумму. Но все работает через раз, не могу понять где ошибся.
var total = 0;
$('.cell input[type="radio"]').change(function () {
let sum = 0;
$('.cell input[type="radio"]:checked').each(function(){
sum += parseInt($(this).val());
});
total = sum;
console.log(total);
$(".price").text(total);
});
$('.cell input[type="radio"]').on('click', function(){
let sum = 0;
if($(this).attr("checked") == 'checked') {
$(this).removeAttr('checked');
sum += parseInt($(this).val());
total = total - sum
$(".price").text(total);
}
else {
$(this).attr('checked', 'checked')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cell">
<input type="radio" id="5d Resume writing" value="100" name="resume writing"/>
<label for="5d Resume writing">$100.00</label>
</div>
<div class="cell">
<input type="radio" id="5d resume editing" value="50" name="resume editing"/>
<label for="5d resume editing">$50.00</label>
</div>
<div class="cell">
<input type="radio" id="5d CV writing" value="100" name="CV writing"/>
<label for="5d CV writing">$100.00</label>
</div>
<div>
<sup>$</sup>
<span class="price">00</span>
<span class="cents">.00</span>
</div>
<div class="cell">
<input type="radio" id="1d Resume writing" value="100" name="resume writing"/>
<label for="1d Resume writing">$100.00</label>
</div>
<div class="cell">
<input type="radio" id="1d resume editing" value="100" name="resume editing"/>
<label for="1d resume editing">$100.00</label>
</div>
<div class="cell">
<input type="radio" id="1d CV writing" value="100" name="CV writing"/>
<label for="1d CV writing">$100.00</label>
</div>
Ответы (1 шт):
Автор решения: Pavel Grishaev
→ Ссылка
let total = 0;
$('.cell :radio').change(function () {
let sum = 0;
$('.cell :radio:checked').each(function(){
sum += parseInt($(this).val());
});
total = sum;
console.log(total);
$(".price").text(total);
});
$('.cell:has(:radio)').on( 'pointerup', function(){
let radio = $(this).find('input'),
checked = radio[0].checked;
if( checked ) setTimeout(()=>{
radio[0].checked = false;
$(radio).trigger('change');
},0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cell">
<input type="radio" id="5d Resume writing" value="100" name="resume writing">
<label for="5d Resume writing">$100.00</label>
</div>
<div class="cell">
<input type="radio" id="5d resume editing" value="50" name="resume editing">
<label for="5d resume editing">$50.00</label>
</div>
<div class="cell">
<input type="radio" id="5d CV writing" value="100" name="CV writing">
<label for="5d CV writing">$100.00</label>
</div>
<div>
<sup>$</sup>
<span class="price">00</span>
<span class="cents">.00</span>
</div>