Search code examples
javascriptjqueryvalidationradiobuttonlist

jquery form validation for dynamic radio groups


Essentially, I need to validate a form that is generated dynamically (unlimited number) and consists of pairs of radio groups. I've made a good progress on it, but I am stuck now. The use case: if the user selects the first radio in a pair, a hidden droplist will appear. The user must choose one of the options from that droplist (but not first option as it is a placeholder text) to make that pair valid. Now, my script is accepting the "please select" as a valid option whereas it should not.

I have a jsfiddle: http://jsfiddle.net/dhLx7hnc/

Here's my jquery:

$(".select-suboption, .see-address").hide();

$('.show').bind('change',function(){

    if ($(this).val() == 1) {
        $(this).siblings('.select-suboption').show();
        $(this).siblings('.see-address').hide();
    } else if ($(this).val() == 2) {
        $(this).siblings('.see-address').show();
        $(this).siblings('.select-suboption').hide();
    } 
});

$(function () {
    $('#validate').click(function () {

        //Make groups
        var names = []
        $('input:radio').each(function () {
            var rname = $(this).attr('name');
            if ($.inArray(rname, names) == -1) names.push(rname);
        });

        $.each(names, function (i, name) {
            if ($('input[name="' + name + '"]:checked').length == 0) {
                alert('Please check ' + name);
            } 
        });
    });
});

Help is very appreciated.


Solution

  • Try

    $(function () {
        $('#validate').click(function () {
    
            //Make groups
            var names = $('input:radio[value="1"]').map(function () {
                return this.name;
            }).get();
    
            $.each(names, function (i, name) {
                var $checked = $('input[name="' + name + '"]:checked');
                if ($checked.length == 0) {
                    console.log('Please check ' + name);
                } else if ($checked.val() == 1 && $checked.nextAll('.select-suboption').find('select').val() == 0) {
                    console.log('Please select suboption for ' + name);
                }
            });
        });
    });
    

    Demo: Fiddle