问题
Need to get the values of checkbox
and need to store in a single variable
by adding all values instead of storing in array.how should i get it.?
here my fiddle and my jquery
function getCheck() {
$('ul.addon > li :checked').each(function() {
allVals.push($(this).val());
});
return allVals;
}
$(function() {
$('ul.addon > li > input').click(getCheck);
getCheck();
$(allVals).each(function(){
addon+=parseInt(allVals);
$('#op').html(addon);
});
});
here allvals array contain al the values of checked checkbox 1,2,1,1,3
Now i need to add those values and move into addon
variable like 1+2+1+1+3=8
and if i uncheck the checkbox the value must be minused i tried my best i did' t able to get it.. :( thanks in advance
回答1:
If you need to add and subtract the value of a checkbox on the checkbox click,try the code below.Hope this is what you meant.
var allVals = [];
$('input:checkbox[name=addons]').each(function() {
allVals.push($(this).val());
});//Gets the complete List of values
//Adds and subtracts the value on click
var curr_value=0;
$("input:checkbox[name=addons]").on('click',function() {
if($(this).is(":checked") == false){
curr_value = curr_value -$(this).val();
}
if($(this).is(":checked") == true){
curr_value = curr_value + +$(this).val();
}
alert(curr_value);//Contains the added values of the checked boxes
});
回答2:
I hope i understand your question well enough, but you want to add the value when checked and minus the value when not checked? Try this:
var value = 0;
$('input[type="checkbox"]').change(function()
{
if($(this).is(':checked'))
{
value += parseInt($(this).val());
}
else
{
value -= parseInt($(this).val());
}
alert(value);
})
On status change of the checkbox i validate the status(checked or not checked). When checked i som the value else i will minus the value.
jsFiddle
来源:https://stackoverflow.com/questions/19244177/retrive-the-checkbox-value-and-how-to-add-the-values-of-checkbox