如何使用JavaScript或jQuery实现单选框值的总和增减计算
Hey there! I see where you're stuck—let's get this sorted out. First, there's a small but critical issue in your HTML that we need to fix first, then we'll tackle the change event logic.
Step 1: Fix the Radio Group Names
Right now, all your radio inputs have empty name attributes. For radio buttons to work as a single group (only one selectable per question), each group needs the same name value. Also, duplicate id attributes are invalid HTML, so I've updated those too:
<div class="form-type-radio"> <strong>Question 1</strong> <div class="form-item"> <input type="radio" id="radio-q1-1" name="q1" value="1" class="form-radio" checked="checked"> <label class="option" for="radio-q1-1">1</label> </div> <div class="form-item"> <input type="radio" id="radio-q1-2" name="q1" value="2" class="form-radio"> <label class="option" for="radio-q1-2">2</label> </div> <div class="form-item"> <input type="radio" id="radio-q1-3" name="q1" value="3" class="form-radio"> <label class="option" for="radio-q1-3">3</label> </div> </div> <div class="form-type-radio"> <strong>Question 2</strong> <div class="form-item"> <input type="radio" id="radio-q2-1" name="q2" value="1" class="form-radio" checked="checked"> <label class="option" for="radio-q2-1">1</label> </div> <div class="form-item"> <input type="radio" id="radio-q2-2" name="q2" value="2" class="form-radio"> <label class="option" for="radio-q2-2">2</label> </div> <div class="form-item"> <input type="radio" id="radio-q2-3" name="q2" value="3" class="form-radio"> <label class="option" for="radio-q2-3">3</label> </div> </div> <div class="form-type-radio"> <strong>Question 3</strong> <div class="form-item"> <input type="radio" id="radio-q3-1" name="q3" value="1" class="form-radio" checked="checked"> <label class="option" for="radio-q3-1">1</label> </div> <div class="form-item"> <input type="radio" id="radio-q3-2" name="q3" value="2" class="form-radio"> <label class="option" for="radio-q3-2">2</label> </div> <div class="form-item"> <input type="radio" id="radio-q3-3" name="q3" value="3" class="form-radio"> <label class="option" for="radio-q3-3">3</label> </div> </div> <div class="total"><strong>Total:</strong><span>3</span></div>
Step 2: Update the JavaScript Logic
Option 1: Efficient Increment/Decrement (Track Previous Values)
This method adjusts the sum by the difference between the new selected value and the old one, so you don't have to re-calculate every radio every time:
var sum = 0; var groupPreviousValues = {}; // Store last selected value for each radio group // Calculate initial sum and track initial selections $('.form-type-radio').each(function() { var groupName = $(this).find('input[type="radio"]').attr('name'); var checkedValue = parseInt($(this).find('input[type="radio"]:checked').val()); sum += checkedValue; groupPreviousValues[groupName] = checkedValue; }); // Update total display initially $('.total span').text(sum); // Handle radio change events $('.form-item input').on('change', function() { var $currentRadio = $(this); var groupName = $currentRadio.attr('name'); var newValue = parseInt($currentRadio.val()); var oldValue = groupPreviousValues[groupName]; // Adjust sum: subtract old value, add new value sum = sum - oldValue + newValue; // Update stored value for this group groupPreviousValues[groupName] = newValue; // Refresh total display $('.total span').text(sum); });
Option 2: Simple Full Recalculation (Easier to Write)
If you prefer a straightforward approach (great for smaller forms), just recalculate the entire sum every time a radio is toggled:
// Helper function to calculate total sum function getTotalSum() { var total = 0; $('.form-item input[type="radio"]:checked').each(function() { total += parseInt($(this).val()); }); return total; } // Initial calculation var sum = getTotalSum(); $('.total span').text(sum); // Change event handler $('.form-item input').on('change', function() { sum = getTotalSum(); $('.total span').text(sum); });
Quick Reminders
- Always pair radio buttons in the same group with matching
nameattributes—this is how browsers enforce single-selection behavior. - Use
parseInt()to convert the radio's string value to an integer, otherwise you'll end up concatenating strings instead of adding numbers. - The first option is more efficient for large forms, while the second is simpler to implement and debug for smaller ones.
内容的提问来源于stack exchange,提问作者Maddie

