Reputation: 95
I have to create a small calculator form by using checkboxes and a select field.
If the user clicks on two checkboxes the select field will update to the option 2 and the total will update to a total figure of 456
Here is my HTML
<div>
<label for="one">1</label>
<input type="checkbox" name="1" id="1" value="228" />
</div>
<div>
<label for="two">2</label>
<input type="checkbox" name="2" id="2" value="228" />
</div>
<div>
<label for="three">3</label>
<input type="checkbox" name="3" id="3" value="228" />
</div>
<div>
<label for="four">4</label>
<input type="checkbox" name="4" id="4" value="228" />
</div>
<div>
<label for="five">5</label>
<input type="checkbox" name="5" id="5" value="228" />
</div>
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="text" name="Total" value="Total">
Here is a fiddle - http://jsfiddle.net/barrycorrigan/se21b1p6/1/
I'm just not sure how to create this in jquery. Any help will be greatly appreciated.
Thanks
Upvotes: 0
Views: 1039
Reputation: 114
this works:
$(function() {
var total = $("input[name='Total']");
var checkBox = $("input[type='checkbox']");
var _select = $("select");
checkBox.click(function(){
checkBox.prop("checked", false);
var _index = $(this).attr("id")
total.val(_index * 228);
_select.val(_index);
checkBox.each(function(){
if (_index > 0) {
$(this).prop("checked", true);
_index--;
}
});
});
_select.change(function() {
checkBox.prop("checked", false);
var _val = $(this).val();
total.val(_val * 228);
checkBox.each(function() {
if (_val > 0) {
$(this).prop("checked", true);
_val--;
}
});
});
});
You can see it in the fiddle: http://jsfiddle.net/yuanzm/se21b1p6/6/
Upvotes: 1
Reputation: 71
you can try with this also
var countChecked = function() {
var n = $( "input:checked" ).length;
$('select >option:eq('+ n +')').prop('selected', true);
sum();
};
countChecked();
function sum() {
var inputs = $('input[type=checkbox]:checked'),
result = $('#total'),
sum = 0;
for(var i=0; i< $('input[type=checkbox]:checked').length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
$(result).val(sum);
}
$( "input[type=checkbox]" ).on( "click", countChecked );
http://jsfiddle.net/amolks/yfat78rL/
Upvotes: 0