I have some checkboxed that I need to get values, and calculate in new elements, but I need that to calculate when is checked and when is not checked.
<div id="dodaci">
<input name="checkboxes1" id="checkboxes-1" value="100" type="checkbox">
<input name="checkboxes2" id="checkboxes-2" value="150" type="checkbox">
<input name="checkboxes3" id="checkboxes-3" value="150" type="checkbox">
<input name="checkboxes4" id="checkboxes-4" value="120" type="checkbox">
<input name="checkboxes5" id="checkboxes-5" value="70" type="checkbox">
</div>
<div id="cena1">750<div>
I need to add values of checked boxes to value in cena1, and i need to get when is not checked to get minus?
Here is jQuery I have so far
$(function() {
$('input[type="checkbox"]').bind('click',function() {
$('#dodaci :checkbox:checked').each(function() {
$('#cena1').append(', '+ $(this).val()); });
});
});
I guess you need something like the below code :
$(function() {
$('input[type="checkbox"]').bind('click',function() {
var value = parseInt($(this).val());
var cenaNum = parseInt($('#cena1').text());
if(this.checked){
$('#cena1').text(value+cenaNum);
}
else {
$('#cena1').text(cenaNum-value);
}
});
});
Here is the working link of fiddle :
Use $('#id:checked')
; which returns true
or false
, so don't bind it to the each()
method and by id I mean an unique ID
like <input name="checkboxes1" id="checkboxes-1">
EDIT
Change:
$('#cena1').append(', '+ $(this).val());
To something like: ( Didn't test!! )
if ($('#id:checked')) {
$('#cena1')
.append(
parseInt($(this).text(), 10) +
parseInt($('#id:checked').val(), 10)
);
} else {
$('#cena1')
.append(
parseInt($(this).text(), 10) -
parseInt($('#id').not(':checked').val(), 10)
);
}
EDIT II
This has nothing to do with your question directly, but it's better to name inputs
the same as its ID
So NOT:
<input name="checkboxes1" id="checkboxes-1">
But:
<input name="checkboxes-1" id="checkboxes-1">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.