views:

314

answers:

1

I have struts 2 checkboxlist as followed:

<s:checkboxlist list="listOfOptions" name="someName" />

I would like to add validation to make sure that at least ONE of the checkboxes has been checked. Any thoughts?

Thanks

A: 

I use JS to do that.

<sx:submit 
            id="button_submit"
            name="button_submit"
            onclick="return validateNotEmptyCheckbox();" /> 

And JS:

function validateNotEmptyCheckbox() {
    var checkboxes = document.getElementsByTagName('input');
    for (i = 0; i < arguments.length; i++) {
        var fieldName = arguments[i];
        var atLeastOne = false;
        for (j = 0; j < checkboxes.length; j++) {
            if ((checkboxes[j].type == "checkbox" || checkboxes[j].type == "radio")
                    && checkboxes[j].name == fieldName
                    && checkboxes[j].checked == true)
                atLeastOne = true;
        }
        if (atLeastOne == false) {
            alert("Choose one!!!");
            return false;
        }
    }
}

Also for radio buttons, as you can see.

Trick