0

I have tried so many options, but nothing has worked.

The main problem is that I have so many check boxes all are generated through php loop, so they have same name and id. I want to check that on submit of that form that at least one should be checked. I have tried so many function so not sure which should be pasted here. So it is better that some one suggest me some fresh answer.

function Validate_Checkbox()
{
    var chks=document.getElementsByTagName('input');   
    var hasChecked = false;
    for (var i = 0; i < chks.length; i++)
    {
        if (chks[i].checked)
        {
            hasChecked = true;
            break;
        }
    }
    if (hasChecked == false)
    {
        alert("Please select at least one checkbox..!");

        return false;
    }

    return true;
}

It is called as onsubmit="return Validate_Checkbox()" in form tag.

Basically I am looking for a JavaScript function.

7
  • it is called as onsubmit="return Validate_Checkbox()" in form tag Commented Aug 24, 2012 at 9:28
  • 1
    so they have same name and id - Ids have to be unique! Commented Aug 24, 2012 at 9:33
  • @Andreas I think he might mean their name is the same as their ID - IDs could still be unique. Commented Aug 24, 2012 at 9:35
  • 3
    Your code here seems to work in isolation: jsfiddle.net/GSD7r Commented Aug 24, 2012 at 9:37
  • Apart from the poor formatting, it does look like the code should work. I haven't tested it though. Does anything happen at all? Commented Aug 24, 2012 at 9:37

4 Answers 4

2

Well your code is OK for the purpose you describe. It could be shorter, but there's no obvious issues with it.

Shortened version

function validate_checkbox() {
    var cbs = document.getElementsByTagName('input');
    for (var i=0, len = cbs.length; i < len; i++)
        if (cbs[i].type.toLowerCase() == 'checkbox' && cbs[i].checked)
            return true;
    alert("Please check at least one checkbox");
    return false;
}

Even shorter version (if you don't care about old IEs)

function validate_checkbox() {
    var checked = document.querySelectorAll('input[type=checkbox]:checked').length;
    if (!checked) alert("Please select at least one checkbox");
    return !!checked;
}

Notes:

1) IDs must be unique - you cannot repeat IDs across multiple elements

2) In JavaScript, it's better (for reasons that are beyond the scope of this post) to put opening curly braces on the same line, not next

3) Avoid capitalising functions unless you plan to instantiate them

Sign up to request clarification or add additional context in comments.

5 Comments

+1 for simplicity, but although curly braces are not mandatory for for-loops or if statements they improve readability a lot and prevents unpleasant results for some cases
Allman style brackets are completely irrelevant in the example, and imo, in any well-written JS code. Either way, posting that the way he writes his code is bad or wrong with no justification as to why just seems like bad form though. It feels like a variation of the "I know best, don't bother your pretty little head with why, just do what I say" attitude. You don't have to include it in your post, but you could at least link to an explanation, such as encosia.com/…
Re: edit - are you really encouraging narrowing the supported browsers of the script AND making less readable code in order to save 3 lines? This isn't a code obfuscation contest.
only the shortest version is working..........any way i am not very keen to support my website in old ie browsers but still can't understand that above longer version is not working .........and a lot of thanks to help me Thanks Utkanos..
You're very welcome. Re: the first approach not working - I had a typo, now corrected. The latter approach is much more graceful, though. Please accept an answer if you consider one of us to have provided the solution.
0

your code will fail if you have other type of input like text or submit button. First you have to check if that is check box.

if (chks[i].type=="checkbox" && chks[i].checked)

Or thing will be easier if you use jQuery

if ($('input:checked').length < 1){
  //Nothing checked
}

1 Comment

Your first point is wrong, for other types of input the line if(chks[i].checked) will evaluate to false as other fields will have undefined for checked which is falsey.
0

function seems to be fine. Are you sure it gets called? Try to debug it using firefox "Firebug". Open firebug->script and then put break point on this function.

Comments

0

Why just check it on submit? I wrote a function using Mootools that is called onchange on each checkbox and checks every checkbox in the same div. If there is no other checkbox checked the user can not uncheck the last checked checkbox.

<input type='checkbox' onChange='validateCheckboxes(this)' name='name' value='val' >

 function validateCheckboxes(elem){
                    var checked = elem.checked;
                    elem.getParent().getElements("input[type=checkbox]").each(function(e){checked += e.checked});
                    if(checked == 0){
                        elem.checked = 1;
                    }
                }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.