JavaScript实现输入框与复选框结果实时求和并显示
Solution for Your JavaScript Calculation & Checkbox Total Update
Hey there! Let's get your code working exactly how you want it—real-time total updates that combine both the input box calculation and selected checkbox values, no more Sum button needed. Here's the revised code with explanations:
Full Revised Code
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" id="myNumber"> <br> <label><input type="checkbox" class="option" value="200" /> Name</label><br /> <label><input type="checkbox" class="option" value="300" /> Blah</label><br /> <label><input type="checkbox" class="option" value="400" /> XYZ</label><br /> <label><input type="checkbox" class="option" value="800" /> Something</label><br /> <label><input type="checkbox" class="option" value="1200" /> Item</label><br /> <br><br> Total : <div id="total">0 $</div> <br>
JavaScript
$(document).ready(function() { // Function to calculate and update the total function calculateTotal() { // Calculate input box product let inputValue = parseInt($('#myNumber').val()) || 0; let inputProduct = 0; if (inputValue >=5 && inputValue <=7) { inputProduct = 97 * inputValue; } else if (inputValue >=8 && inputValue <=10) { inputProduct = 87 * inputValue; } else if (inputValue >=11) { inputProduct = 82 * inputValue; } // Calculate selected checkboxes sum let checkboxSum = 0; $('.option:checked').each(function() { checkboxSum += parseInt($(this).val()); $(this).parent().css('background', 'gold'); }); $('.option:not(:checked)').each(function() { $(this).parent().css('background', '#fff'); }); // Combine both values and update total const total = inputProduct + checkboxSum; $('#total').html(total + ' $'); } // Trigger calculation on input box change $('#myNumber').on('input', calculateTotal); // Trigger calculation on checkbox click $('label').click(calculateTotal); // Initialize total on page load calculateTotal(); });
Key Changes Explained
- Removed the Sum Button: We replaced it with an
inputevent listener on the number box, so every time the user types or changes the number, the total updates instantly. - Combined Calculation Logic: All the math (input product + checkbox sum) lives in one
calculateTotalfunction, so both input changes and checkbox clicks trigger the same update process. - Handled Empty Input: Used
parseInt($('#myNumber').val()) || 0to make sure if the input is empty, it treats the value as 0 instead of breaking the calculation. - Removed Unused Elements: Got rid of the
#demoparagraph since we're now showing the combined total directly in the#totaldiv. - Initialization: Called
calculateTotal()on page load to set the initial total to 0, which matches your starting state.
Testing this: if you enter 5 and check the "Name" checkbox, you'll see the total update to 685 ($485 + $200) right away—no button clicks needed!
内容的提问来源于stack exchange,提问作者Sheldon Cooper
相关产品推荐
相关产品推荐

