codeSeven
codeSeven

Reputation: 469

JS - Find radio buttons that are not checked in Table

I have here a table with a looping of checkbox which can select score in particular description, however my problem is form validation. i just want to check if all checkboxes are checked, if not i want to display a message depends on the row when checkbox is not checked. i have a span here which the id is "Message" and i want to display the error message.

   <table class="table table-sm table-bordered table-condensed mt-3 kra-table" id="kra-table" style="padding:20px;">
                    <thead>
                        <tr>
         <th><i class="fas fa-key" style="color:#A9A9A9;"></i> Key Result Areas(KRA)</th>
         <th>Never exhibits skill (1)</th>
         <th>Rarely exhibits skill (2)</th>
         <th>Occasionally exhibit skill (3)</th>
         <th>Almost everytime exhibit skill (4)</th>
         <th>Every time exhibits skill (5)</th>
     </tr>
     </thead>
           <tbody>
          @{
          for (int i = 0; i < deserialized.Table.Count; i++)
            {
              cname++;
              var name = "score" + i;
               <tr>
        <td><span id="Message"></span> <h6 class="kra_description">@deserialized.Table[i].KRA_DESCRIPTION </h6><input type="hidden" name="KRA_CODE" id="KRA_CODE" value="@deserialized.Table[i].KRA_CODE" />  </td>

      @for (int j = 0; j < 1; j++)

                 {

       <td><center><input type="radio" class="Score" name="@name" value="1" /></center></td>
       <td><center><input type="radio" class="Score" name="@name" value="2" /></center></td>
       <td><center><input type="radio" class="Score" name="@name" value="3" /></center></td>
       <td><center><input type="radio" class="Score" name="@name" value="4" /></center></td>
       <td><center><input type="radio" class="Score" name="@name" value="5" /></center></td>
                                    }

                                </tr>
                            }        
                   }        
          </tbody>
         </table>

Upvotes: 0

Views: 56

Answers (1)

Đinh Carabus
Đinh Carabus

Reputation: 3496

You could just loop over each row and check if it contains a checked radio-input. If it doesn't you display the error message:

function isValid() {
  var valid = true;

  $("#kra-table tbody tr").each(function() {
    if (!$(this).find('[type="radio"]:checked').length) {
      valid = false;

      // .. show error message for row here somehow
      $(this).find('.message').show();
    }
  });

  return valid;
}

You should not use an ID "Message" on each row (IDs must be unique across the document). Instead you should use a class for that.

Upvotes: 2

Related Questions