Calculating the sum of radio buttons, displaying the sum, and passing to external Beanstream server

830 Views Asked by At

I am a novice web developer and I need to calculate the sum of some radio buttons with different values, then pass that result to an external payment server.

This is what one of the radio buttons looks like:

<div class='container'>
<label for='p_board_rental' ><strong>Paddleboard Rental</strong> (limited amount available*: </label><br/>
<input type='radio' name='rental' value='0'/><label class="radio"> No</label><br/>
<input type='radio' name='rental' value='20'/><label class="radio"> Yes</label><br/>

I need the final result calculated and then displayed but I have tried so many ways and I cannot get it to work properly! The best I can get is the empty box where the total SHOULD be appearing.

2

There are 2 best solutions below

0
Matt Mombrea On

If you're using jQuery you can do something like:

function tallyValues(){
    var tally = 0;
    $('input:radio').each(function(){
        if($(this).is(':checked')){
         tally += parseInt($(this).val());
        }
    });
}

tally will hold the sum of the selected values

0
Mark Hardin On

This should get you close to where you want to be. Simply loop over all the radio buttons, if it's checked shove it into an array if it doesn't already exist in the array. Then at the end calculate the total and set it in the textbox.

There may be some jquery functions to make this a little more elegant.

var array = new Array();

$(":input[type='radio']", "#containerOfChoice").each(function () {
    if ($(this).is(':checked')) {
        var value = $(this).attr("value");
        if ($.inArray(value, array) == -1) {
            array.push(value);
        }
    }
})

var total = 0;
for (var i = 0; i < array.length; i++) {
    total += parseInt(array[i]);
}

$("#textBoxOfChoice").val(total);