Pages

Tuesday, May 6, 2014

jQuery multiple radio fields validation of groups

- I have below options for input radio fields:

<input type="radio"  name="option1" value="1" />
<input type="radio"  name="option1" value="2" />
<input type="radio"  name="option1" value="3" />
<input type="radio"  name="option1" value="4" />
                                           
<input type="radio"  name="option2" value="5" />
<input type="radio"  name="option2" value="6" />
<input type="radio"  name="option2" value="7" />
<input type="radio"  name="option2" value="8" />

<input type="radio"  name="option3" value="9"  />
<input type="radio"  name="option3" value="10" />
<input type="radio"  name="option3" value="11" />
<input type="radio"  name="option3" value="12" />

<input type="radio"  name="option4" value="13" />
<input type="radio"  name="option4" value="14" />
<input type="radio"  name="option4" value="15" />
<input type="radio"  name="option4" value="16" />


- Please write below jQuery for all radio fields:

var radioNames = []
    $('input[type="radio"]').each(function () {
        var radioName = $(this).attr('name');
        if ($.inArray(radioName, radioNames) == -1) radioNames.push(radioName);
    });

    // validation for each radio group
    $.each(radioNames, function (i, fieldName) {
        if ($('input[name="' + fieldName + '"]:checked').length == 0) {
            console.log('Please check ' + fieldName);
        }
    });

No comments: