BumbleBee
BumbleBee

Reputation: 10839

Check all the radio buttons checked and get their values JQuery

Using JQuery I am trying to perform validation and also get the values of all the dynamically generated Radio buttons in the page.

I have 10 questions on my page and each question has a Radio button group(YES/NO).

On click event of the Continue button I need to check all the questions are answered or not and also get the answers for all the questions.

this is how each question look like.

 <tr>
     <td class="TextBold">1.</td>
     <td class="TextBold">Question content 1
    </td>
    <td class="TextBold">
    <table id="ctl00_DefaultContent_ctl01" border="0">
      <tr>
       <td>
         <input id="ctl00_DefaultContent_ctl01_0" type="radio" name="ctl00$DefaultContent$ctl01" value="Yes" /><label for="ctl00_DefaultContent_ctl01_0">Yes</label>
       </td>
       <td>
    <input id="ctl00_DefaultContent_ctl01_1" type="radio" name="ctl00$DefaultContent$ctl01" value="No" /><label for="ctl00_DefaultContent_ctl01_1">No</label>
       </td>
      </tr>
     </table>
    </td>
    </tr>

Here is what I have come up with. But I would like to give a warning to the user saying these questions are not answered without making another selector call.

$('#btnContinue').click(function () {
    if ($(":radio:checked").size() < 10)
{

}
    var result = '';
    $('input:checked').each(function () {
        result += "|" + $(this).closest('table').closest('td').prev().prev().html() + ',' + $(this).val();
    });
    alert(result);
}); 

Upvotes: 0

Views: 6950

Answers (3)

elijah
elijah

Reputation: 2924

the checked radio buttons will be in the array returned by

$('input:radio:checked')

so, if that array is 10 items long, all questions have been answered. And for each item in that array, .val() will give you the value of the selected radio.

Upvotes: 2

Rafay
Rafay

Reputation: 31043

if($(":radio:checked").size()<10)
 //validation fails

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can try this.

if($('input:radio:checked').length != ($('input:radio').length/2)){
   //All the questions are not answered
}

Of course you can restrict the selector by passing a parent container as a context just to make sure it will select only the radio buttons within that container.

Upvotes: 4

Related Questions