开发者

How to check with Javascript if all 'SELECT' values equal 1 inside a form?

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 sel开发者_Go百科ected option value of 1
    </div>
</form>


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" );


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜