Steve
Steve

Reputation: 14922

JQuery quiz: count the number of repeat value from group of answers?

I have a form with a series of questions, radio buttons. Each group is the same 5 values, order scrambled so user doesn't see pattern.

When the user clicks a button, I want to first get the value of each group (which I think I know how to do with $('input:radio[name=bar]:checked').val();) and then see how many total of each string was picked.

As in this sample question:

<input type="radio" name="q1" value="loner">
<input type="radio" name="q1" value="partier"
<input type="radio" name="q1" value="clueless">
<input type="radio" name="q1" value="romantic">
<input type="radio" name="q1" value="pragmatic">

So, I have maybe 10-20 questions with answers, which are mapped to these (made up here) values. At the end, the user clicks a button and will need to total up the number of times each of the 5 terms was chosen, see which was chosen the most, as in "you are a romantic".

I hope this is clear.

Upvotes: 1

Views: 427

Answers (1)

biziclop
biziclop

Reputation: 14626

Example:

http://jsfiddle.net/mM7X4/

var values = ['loner','partier','clueless','romantic','pragmatic'];
var result = [];

$.each( values, function( i, value){
  result.push({
    value: value,
    sum: $('input:radio[value='+value+']:checked').length;
  });
});

result.sort( function( a,b){
  if( a.sum < a.sum ) return +1;
  if( a.sum > a.sum ) return -1;
  return 0;
});

alert('You are a '+result[0].value );

Upvotes: 1

Related Questions