JPB JPB - 21 days ago 7
HTML Question

Adding integer values from a radio form

I am trying to create a checklist that provides a total number of points based on the value of the radio button selection (with jquery). The score for each input varies.

I can get the individual values but not sure how to add them up?



/* jquery */

$(document).ready(function(){

function setScore() {
var score = $('input:checked').val();
$('#score').text(score);
}

// set score on input change
$('input').change(setScore);

// set score on initialization
setScore();

});

<li>
<label>Facebook link?</label>
<input type="radio" class="radio" name="Facebook" value="4">Yes</input>
<input type="radio" class="radio" name="Facebook" value="-4">No</input>
</li>

<li>
<label>Instagram link?</label>
<input type="radio" class="radio" name="Instagram" value="6">Yes</input>
<input type="radio" class="radio" name="Instagram" value="0">No</input>
</li>

<span>Score: <span id="score"></span></span>





Thanks.

Answer

Try changing the setScore function to:

function setScore() {
    var score = 0;
    $.each($('input:checked'), function (i,input) { score += Number( input.value);});
    $('#score').text(score);
}

(Assuming there are no checkbox inputs that need to be excluded)