Reputation: 177
I have a problem with adding up values when on click function is performed.
I have simple radio buttons:
<input type="radio" name="product1" class="price" value="4" /> 4
<input type="radio" name="product2" class="price" value="6" /> 6
I would like to add up values when click is performed. Obviously I can get values on click but I don't know how to add them up.
$('.price').click(function() {
price = $(this).val();
}
OK, other issue.
What if we have two separate click functions like this:
<input type="radio" name="product1" class="price" value="4" /> 4
<input type="radio" name="product2" class="price" value="6" /> 6
<input type="radio" name="product1" class="number" value="3" /> 3
<input type="radio" name="product2" class="number" value="7" /> 7
and
$('.price').click(function() {
price = $(this).val();
}
$('.number').click(function() {
number = $(this).val();
}
How to add up values from .price radio and .number radio? On top of that make sure you can only add one value from each, not that it will be adding all values regardless of which group of radio buttons?
Upvotes: 0
Views: 2979
Reputation: 9888
I don't think I understand the question in terms of elements employed to show/select prices, so I'll just add few hints with the hope that they will be useful:
To select all radio buttons of given name (e.g. "product1"), you do:
$('input:radio[name="product1"]')
To select all radio buttons of givan name, that are checked (there can be only one):
$('input:radio[name="product1"]:checked')
To select all checked radio buttons regardless of the name:
$('input:radio:checked')
Function to sum up all values (parse-able as numbers) in a jQuery collection of input elements:
function sumValues($inputs) {
var sum = 0;
$inputs.each(function () { sum += +this.value; });
return sum;
};
Your handler then should look something like this (insert appropriate selector):
$(<whatever-triggers-recalc>).click(function() {
// change selector to the one that selects the radios you need summed
var sum = sumValues( $('input:radio[name="product1"]') );
// here, you have your sum
});
You don't want to update the sum (on an event), instead you need to recalculate it every time.
You probably dont need classes
, the name
attribute should suffice if it is enough to identify the information that is to be sent to the server.
I hope these are helpful.
Upvotes: 0
Reputation: 79830
Try
var price = 0;
$('.price').click(function() {
price += parseInt($(this).val(), 10);
}
Upvotes: 2