T.T.T.
T.T.T.

Reputation: 34523

Javascript check box validation and length

Have check boxes 1-300. This JS function alerts user when nothing is selected. Function works great for the first 290 elements. For example, when item 291 is selected it alerts that nothing is selected. document.checks.user.length is coming out to 298, not sure why that is either. Any suggestions? Thanks.

function sub_delete() //Submit & Validation for delete 
{  
    alert ( document.checks.user.length); 298?

    for (i = 0; i < document.checks.user.length; i++) //for all check boxes
    {
        if (document.checks.elements[i].name == "user" && document.checks.elements[i].checked == true ) //otherwise elements also looks at radio buttons 
        {
            document.checks.submit();
            return 0;
        }
    }

    //If we get here no delete was (true) selected
    alert ( "Select Data to Delete" );
    return 0; 
}

Upvotes: 0

Views: 2569

Answers (2)

Zabbala
Zabbala

Reputation: 2203

You're iterating over the elements of document.checks.user, however you're checking document.checks.elements[i] for name and value ('checked-ness').

Upvotes: 1

Greg
Greg

Reputation: 321618

You're not looking at the same thing you're looping over.

for (i = 0; i < document.checks.user.length; i++) //for all check boxes
{
    if (document.checks.user[i].name == "user" && document.checks.user[i].checked == true ) //otherwise elements also looks at radio buttons 
    {
            document.checks.submit();
            return 0;
    }
}

Try that instead.

For this many elements it's probably best not to recalculate .length each time, too.

Upvotes: 1

Related Questions