IluTov
IluTov

Reputation: 6862

Validate radio buttons with jQuery on submit

I want to validate my form using jQuery. It has groups of radio buttons.

I have found multiple solutions for a single group of radio-buttons or solutions, where you have to specifically say what group-names there are.

Like here: Validate radio buttons with jquery?

The problem is, that the form is being generated at run-time. The questions are saved in a txt file (don't ask, it's a school exercise). The generated HTML-Code looks something like this:

<p>What&#039;s your gender? 

<input type="radio" name="gender" value="m" />Male 
<input type="radio" name="gender" value="f" />Female 

</p>

<p>

How satisfied are you with out support? 
<input type="radio" name="satisfaction" value="0%" />Not at all 
<input type="radio" name="satisfaction" value="25%" />Not very much 
<input type="radio" name="satisfaction" value="75%" />It was ok 
<input type="radio" name="satisfaction" value="100% />It was very satisfying

</p>

The js file is being generated using Twig, so it would be possible to loop through all the radio button groups, but I would like to avoid this if that's possible.

Upvotes: 1

Views: 1944

Answers (2)

IluTov
IluTov

Reputation: 6862

I got it working like this

var groups = [];
$(function() {
    $("input[type=radio][name]").each(function() {
      // Add the unique group name to the array
      if (groups[groups.length - 1] != $(this).attr("name")) groups.push($(this).attr("name"));
    });
});
$('form').submit(function () {
    var isValid = true;

    $.each(groups, function(i, o) {
      // For each group, check at least one is checked
      if (isValid) isValid = $("input[name='"+o+"']:checked").length;  
    });

    if (!isValid) return false;

    return true;
});

Thanks to Blade0rz!

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78595

You would need to add all the groups first (page load would be fine, but make sure the group array is in global scope), then validate each group individually when your form is submitted/button click

var groups = [];
$(function() {
    $("input[type=radio][name]").each(function() {
      // Add the unique group name to the array
      groups[$(this).attr("name")] = true;
    });
});
$("button").click(function() {
    $.each(groups, function(i, o) {
      // For each group, check at least one is checked
      var isValid = $("input[name='"+i+"']:checked").length;
      alert(i + ": " + isValid);
    });
});

Upvotes: 1

Related Questions