Summation of points and adding to the graduated result

I have a rating form that allows people to be scored and then placed in a graduated group, but I find it hard to understand how this can be done using jQuery or JavaScript.

For example, the first part of my form has a structure where the total values ​​from each group should be written in the field CombinedScore.

<input id="Food1" name="Food" type="radio" value="5" />
<input id="Food2" name="Food" type="radio" value="10" />
<input id="Food3" name="Food" type="radio" value="15" />

<input id="Drink1" name="Drink" type="radio" value="5" />
<input id="Drink2" name="Drink" type="radio" value="10" />
<input id="Drink3" name="Drink" type="radio" value="15" />

<input name="CombinedScore" type="text" />

The second part is to check the value of the combined account and place it in the appropriate group. for instance

<input id="FoodDrinkGroup1" name="FoodDrinkGroup" type="radio" value="1-10" />
<input id="FoodDrinkGroup2" name="FoodDrinkGroup" type="radio" value="11-20" />
<input id="FoodDrinkGroup3" name="FoodDrinkGroup" type="radio" value="21-30" />

So, if someone credits 10 for food and 15 for drinks, they should be added to 21-30 FoodDrinkGroup.

In general, I have three groups like this, but I hope that if I can get it to work for one, I should use the same code for the rest.

+3
3

, ,

$(function() {
    // Part 1
    var sum = parseInt($('input[name="Food"]:checked').attr('value'));
    sum += parseInt($('input[name="Drink"]:checked').attr('value'));
    $('input[name="CombinedScore"]').val(sum);

    //Part 2
    $('input[name="FoodDrinkGroup"]').each(function(i, elem) {
        var range = $(elem).attr('value').split('-');
        if (sum >= range[0] && sum <= range[1]) {
            $(elem).attr('checked', true);
        }
    });
});

JSFiddle

+1

. , , . . - http://jsfiddle.net/YUwUG/

function proc() {

    food = $('input[name=Food]:checked').val();
    drink = $('input[name=Drink]:checked').val();

    combined = parseInt(food) + parseInt(drink);

    $("#combined").val(combined);

    if (combined < 11) {
        $('#FoodDrinkGroup1').attr('checked', 'checked');
    } else if (combined < 21) {
        $('#FoodDrinkGroup2').attr('checked', 'checked');
    } else if (combined < 31) {
        $('#FoodDrinkGroup3').attr('checked', 'checked');
    }

}
0

A bit late, but I thought I'd show the code that I generated. It just uses a bit of math to determine which group and, therefore, which index element it should select.

var total = 0;

$('input[name=Food]:checked, input[name=Drink]:checked')
 .each(function() {
    total += parseInt(this.value);
});

var index = parseInt(total / 11);

$('[name=CombinedScore]').val(total);

$('input[name=FoodDrinkGroup]').eq(index).prop('checked', true);

Working scenario: http://jsfiddle.net/garreh/5j7Jd/

0
source

All Articles