简体   繁体   中英

How to get all radio button group selections from a form submit

I have a form with many groups of radio buttons which are dynamically generated from a database of questions. They look like this:

<input name="group{{../questionNumber}}" type="radio" id="q{{../questionNumber}}_{{answerLetter}}" value="{{answerLetter}}" />

where ((questionNumber}} is just an integer (they go in order from 1) and {{answerLetter}} will be a letter starting from A again for each new question, meaning that question 1, answer 2 will have name="group1" and id=q1_B .

When the user submits the form I would like to get all their answers, but so far I only know how to get an answer by explicitly typing out the name properties value:

Template.Test.events({
  "submit #Test": function (event, template) {

    // var element = template.find('input:radio[name=group1]:checked');
    // alert($(element).val());

    alert(event.target.group1.value)

    return false;
  }
});

#Test is the form id .

How could I dynamically get all the value values into an array? Also can I get the number of radiobutton groups easily inside the above function or is it easier to query that from my database?

You can find all checked radios whos name starts with "group" this way:

var groups = {};
$('#Test').find('input[name^="group"]:checked').each(function(){
    var this_name = $(this).attr('name');
    var this_value = $(this).val();
    groups[this_name] = this_value;
});

Now the found radios are they keys of the object groups so you can count them like so:

var count = 0;
for (var k in groups) 
    if (groups.hasOwnProperty(k)) 
        ++count;

The radio values are the values of the keys in that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM