简体   繁体   中英

Jquery validation for <li> of multiple <ul>

I have an HTML structure like this which contains some checkboxes and radio buttons

<div class="companyQuestions">
    <h4 class="subHead">Company Questions</h4>
    <span class="question">Question 1</span>
    <ul class="selectFrame special">
        <li><input type="checkbox" name="rent_or_own" value="rent" /></li>
        <li><input type="checkbox" name="rent_or_own" value="own" /></li>
        <li><input type="checkbox" name="rent_or_own" value="both" /></li>
        <li><input type="checkbox" name="rent_or_own" value="none" /></li>
    </ul>
    <span class="question">Question 2</span>
    <ul class="selectFrame multipleLines">
        <li><input type="checkbox" name="services_in_particular_area" value="central"/></li>
        <li><input type="checkbox" name="services_in_particular_area" value="east" /></li>
        <li><input type="checkbox" name="services_in_particular_area" value="west" /></li>                                    
        <li><input type="checkbox" name="services_in_particular_area" value="europe" /></li>
    </ul>                                
    <span class="question">Question 3</span>
    <ul class="selectFrame special">
        <li><input type="radio" name="store_sensitive_information" value="yes" /></li>
        <li><input type="radio" name="store_sensitive_information" value="no" /></li>
        <li><input type="radio" name="store_sensitive_information" value="not_sure" /></li>
    </ul>
</div>

I want to make sure atleast one input element of each <ul> is selected. I had following script for that validation.

<script>
    $(':input.labelauty').change(function(){
        $(this).parent().parent().addClass('chosen');
    });

    var chosen_flag = 1;
    $(".selectFrame").each(function(){
        if(!($(this).hasClass("chosen"))){
            chosen_flag = 0;;
        }
    })
    if (!chosen_flag) {
        alert('Answer All Questions');
    }
    else{
        alert('Congratulations. Your form is submitted');
    }
</script>

This works fine for radio button. But for check boxes if select and deselect item this script breaks. I have tried some other solutions too but it was in vain. Please help me with some logic for this. Thanks in advance :)

Fiddle Demo

var ul = $('.selectFrame'), //cache selector
    len = ul.length;     //length of all ul
ul.find('input').change(function () { //change event on input inside ul
    if (ul.has('input:checked').length == len) alert('done'); //if ul having checked checkbox is equal to all ul length than do something
    else alert('Answer All Questions');
});

.change()

.has()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM