Reputation: 53
So here's the problem. I have two check boxes, and two text boxes, and one final text box at the bottom. What I'm trying to do is this: When check box 1 is checked, the text box right next to it gets a value of 8. When check box 2 is checked, the text box right next to it gets a value of 7. Then finally the final text box shows the sum of the text boxes, which in this case should be 15.
I've tried this: just give the text boxes values with if statements. Then give a class "textboxes" for both text boxes, and just count the sum of them. I'm able to get the values with if statements, but can't get the final sum of those.
$(function(){
$('#checkbox1').click(function(){
if (this.checked) {
$('#textbox1').val(7);
}
});
$('#checkbox2').click(function(){
if (this.checked) {
$('#textbox2').val(8);
}
});
var total = 0;
$('.textboxes').each(function() {
total += Number($(this).val());
});
$('#totalSum').val(total);
});
Upvotes: 1
Views: 3278
Reputation: 8781
EDIT: Cleaner and more extendable code (works for any dynamic number of checkboxes):
$(function(){
$(':checkbox').click(function(){
var textbox = $(this).next('input[type="text"]');
if (this.checked) {
$(textbox).val($(this).data("number"));
}
else{
$(textbox).val("");
}
calculateTotal();
});
});
function calculateTotal()
{
var total = 0;
$("input:checked").each(function(){
var val = $(this).next('input[type="text"]').val();
total += Number(val);
});
$('#totalSum').val(total);
}
data-number attributes are added to the checkboxes:
<div>
<input type="checkbox" id="checkbox1" data-number="7" />
<input type="text" id="textbox1" />
</div>
<div>
<input type="checkbox" id="checkbox2" data-number="8" />
<input type="text" id="textbox2" />
</div>
<div>
<input type="checkbox" id="checkbox3" data-number="9" />
<input type="text" id="textbox3" />
</div>
<div>
<input type="checkbox" id="checkbox4" data-number="10" />
<input type="text" id="textbox4" />
</div>
<input type="text" id="totalSum" />
Upvotes: 1
Reputation: 82287
The total only calculates once, on page load, and it calculates 0. What you want to do is update the total each time the input is changed. You can do this by making the total a function, and then calling that from the click callback
$(function(){
$('#checkbox1').click(function(){
if (this.checked) {
$('#textbox1').val(7);
updateTotal();
}
});
$('#checkbox2').click(function(){
if (this.checked) {
$('#textbox2').val(8);
updateTotal();
}
});
function updateTotal(){
var total = 0;
$('.textboxes').each(function() {
total += Number($(this).val());
});
$('#totalSum').val(total);
}
updateTotal();
});
.textboxes{
width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<input class="textboxes" id="textbox1" /><input id="checkbox1" type="checkbox"/><br />
<input class="textboxes" id="textbox2" /><input id="checkbox2" type="checkbox" /><br />
</div>
<div><input id="totalSum"></div>
Upvotes: 2