0

Is it possible to check if all select values inside a div, inside a form equals 1? I don't want to write hundreds of if statements. Reason for this is that I am trying to validate the form, and want to check so that the user has selected something. Standard value in EVERY select list is 1 (not selected anything).

<form name="myform" onchange="return jsfunction();" etc...>
    <div id="formdiv">
        many many selects, all having a selected option value of 1
    </div>
</form>

2 Answers 2

1

Not writing the code

Get all select elments using

document.getElementsByTagName ( 'select' );

which returns an array.

Loop through the array and get the selected value and check those.

To get the selected value you can use

document.getElementById ( elementinArrayIndex.id ).value;

where elementinArrayIndex is the select element in the current loop iteration.

If all the select elements that you want to check are inside the div element with id "formdiv" then you can use

document.getElementById ( "formdiv" ).getElementsByTagName ( "select" );
Sign up to request clarification or add additional context in comments.

1 Comment

just a question... Could you write the loop quickly, so that I understand how to loop through an array like you mentioned? Thanks
0

If you want to know if all of the boxes are checked, get them all with a

var selects = document.getElementsByTagName('select');

then loop through and count them

var checked = 0;
for(var i in selects)
{
    checked += selects[i].value;
}

if checked is equal to the number of select boxes, they're all checked.

if(checked == selects.length)
{
   //yay
}

beware of course that if there are lots of select boxes, this may take a while, but there isn't a great deal you can do about that. If you do run into a performance related problem, your selection system is possibly over complicated...

Comments

Your Answer

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