Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have multiple checkbox, and all of it must be checked. i write down the code but it doesnt work.

this is the code html sample::

    <form name="pembres" id="pembres" method="POST" onSubmit="return validateform()"   style="margin:0;"> 
    <input type="checkbox" name="lanjut[]" value="setuju2"  />
    <input type="checkbox" name="lanjut[]" value="setuju3"  />
    <input type="checkbox" name="lanjut[]" value="setuju4"  />
    <input type="checkbox" name="lanjut[]" value="setuju5"  />
    <input type="submit" value="Next Step" name="next" />
    </form>

1st script at head tag

<script type="text/javascript">
        function validateform(){
            var success = false;
                for (i = 0; i < document.pembres.elements['lanjut[]'].length; i++){
                    if (document.pembres.elements['lanjut[]'][i].checked){
                        success = true;
                    }
                }
            return success;
        }
    </script>

2nd script before /body

    <script type="text/javascript">  
var form = document.getElementById('pembres');
form.onsubmit = validateForm;

function validateForm() {
    var isValid = false,
        form = this,
        els = form.elements['lanjut[]'];
        i;
    for (i = 0; i < els.length; i += 1) {
        if (els[i].checked) {
            isValid = true;
        }
    }
    return isValid;
}
</script>
share|improve this question
    
Your code is saying if one is checked, not all. –  epascarello Feb 20 '14 at 2:49
    
can u help me to make it all checked ? –  user3330800 Feb 20 '14 at 2:51
    
do the opposite logic... –  epascarello Feb 20 '14 at 2:59

1 Answer 1

You are setting isValid to true if any checkbox is checked, what you should do is return false if any checkbox is not checked.

function validateForm() {
    var form = this,
    els = form.elements['lanjut[]'], i;
    for (i = 0; i < els.length; i += 1) {
        if (!els[i].checked) {
            return false;
        }
    }
    return true;
}
share|improve this answer
    
May be there should be "var" in front of "form = " to prevent putting those variables in global scope. –  Du D. Feb 20 '14 at 3:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.