Reputation: 69
I want to get the average by input radio button value.
I have a form with 3x 10 radio fields counting from 1 to 10.
Now I want to calculate the average, so you get a final score.
I get it working with a text field, but I don't know how to do it with radio buttons checked.
This is my javascript:
$('.beoordeling').keyup(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
I have created a jsfiddle with how I have it now. http://jsfiddle.net/Q2MEq/
Upvotes: 0
Views: 741
Reputation: 7977
Please check this
$('.beoordeling').keyup(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
Demo: JSFiddle
Upvotes: 1
Reputation: 74738
See for this you need to have radio
buttons with different name
attributes or without it, and then you can change to this:
$(':radio').change(function () {
var total = 0,
valid_labels = 0,
average;
$(':checked').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
Upvotes: 1
Reputation: 20646
Check this code.
$('.beoordeling').change(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling:checked').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
change
events in case of inputs like radio and not keyup.:checked
selector to get selected radio buttons only.Upvotes: 1
Reputation: 43
You can determine whether or not a radio button is checked with ".checked"
document.getElementById("radio_1").checked
... will return true if the button is checked, false otherwise.
Upvotes: -1