开发者

JQuery Validate and Checkbox Click Function

开发者 https://www.devze.com 2023-02-03 03:06 出处:网络
I have a basic checkbox click function that only allows the user to click only one checkbox within each fieldset (there are four fieldsets each containing numberous checkboxes:

I have a basic checkbox click function that only allows the user to click only one checkbox within each fieldset (there are four fieldsets each containing numberous checkboxes:

$(document).ready(function(){

$('input[type=checkbox]').click(function(){

    // get the fieldset class
    var fieldset = $(this).parents('fieldset').attr('class');

    // set the number of checked
    var numChecked = $('.'+fieldset+' input:checked').size();

    // if more than 1
    if(numChecked > 1){
        alert('Please select only one option per breakout session.')

$(this).attr('checked',false); }

}); 

Then I have a submit function on the form that will confirm that at least one checkbox is selected before posting the form:

$('form[name=mainForm]').submit(function(){

    var error = '';

    // loop through each fieldset
    $('fieldset',this).each(function(){

        // set the number of checked for this fieldset
        var numChecked = $('input:checked',this).size();

        // if none are checked
        if(!numChecked){
            // set the error var
            error = 'At least one of your time sessions has no checkbox selected!';
            // add class to show user
            $(this).addClass('errorSessions');
        }
        else{
            $(开发者_StackOverflowthis).removeClass('errorSessions');
        }

    });

    // if any errors, show them and don't allow the form to be submitted
    if(error.length){
        alert(error);
        return false;
    }

   $("#mainForm").validate();

The form validates perfectly and everything happens flawlessly the first time around. The problem is that if you submit the form, the validation occurs and it gives the error "At least one of your time sessions has no checkbox selected!" - at that point if you proceed to select multiple checkboxes within a given fieldset that was not initially checked, it will ignore the checkbox click function and allow you to select more than one checkbox in a fieldset.

Can someone please help with this?


Okay, I figured it out. The error has to do with the script adding the class 'errorsessions' to the fieldset which changes the unique classname of the fieldset. By adding a unique id to each fieldset and then changing the script to reference .attr('id'); instead of .attr('class'); the issue resolved and the on click alert function resumed after the class was added.


Do you consider using radio buttons as they are there for single selection? This way you don't have to check for multi selection as it isn't possible for select more than one radio button in given group.

0

精彩评论

暂无评论...
验证码 换一张
取 消