[thelist] Javascript/Dropdown box detection

Tom Dell'Aringa pixelmech at yahoo.com
Tue Sep 9 20:25:31 CDT 2003


--- CDitty <mail at redhotsweeps.com> wrote:
> I am trying to detect if the user has selected something from a
> multi drop down box and also if they have selected just one item.  
> I cannot get the JS to detect it and to give me an alert.  Can 
> anyone look at the code below and tell me what I am doing wrong?

Chris,

There are many problems with the script and how you are doing things,
so I'll try and help you clean them up.

> <script LANGUAGE="JavaScript">
> function multiMeterCheck(form){
>  alert('1');
>    if(form.acct.options[form.acct.selectedIndex].text == ""){

This is not the correct way to get the text value, nor is it a
particularly good way to address the objects. The best way is to use
the form and elements array, which are DOM lvl 0 compliant and work
flawlessly. First I would set my drop as a variable.

   var myDrop = document.forms['multi'].elements['acct[]'];

Shortened by passing the form on your function call:

   var myDrop = myForm.elements['acct[]']'

Secondly, your reference to the text is slightly off:

   if(myDrop[myDrop.selectedIndex].text == "")..

You do not refer to the options when you are grabbing the text.

>    alert('You must select atleast 2 meters.');
>    return(false);

The correct expression i:

   return false; (no brackets)

>    }
>  alert('2');
> }
> </script>

Now, your if condition is NOT going to tell you whether or not 2
items have been selected. It is only going to tell you whether or not
the selected index's text is equal to a blank string.

To see if a single choice has been made, you could check against a
value of -1 (which tells you there is no selected index:

   var choice = oSelect.selectedIndex;
   if (choice == -1)... some stuff for no choice...

Now you want to check and see if there are TWO choices. I think what
you want to do is iterate through the multi-select (which is what you
have) and tick a variable to see how many choices you have. This is
what I would do:

function multiMeterCheck(myForm)
{
	var myDrop = myForm.elements['acct[]'];
	var selectCount = 0;
	var dropLength = myDrop.length
	for(var i=0; i<dropLength; i++)
	{
		if(myDrop.options[i].selected == true)
		{
			selectCount++;
		}
	}
	
	if(selectCount<2)
	{
		alert('You must select at least 2 meters.');
		return false;
	}
	return true;
}

I did a *quick* test and it worked for me. Let me know how it works
for you or if you have any questions.

HTH

Tom




=====
http://www.pixelmech.com/ :: Web Development Services
http://www.DMXzone.com/ :: Premium Content Author / JavaScript / Every Friday!
http://www.maccaws.com/ :: Group Leader
[Making A Commercial Case for Adopting Web Standards]

"That's not art, that's just annoying." -- Squidward


More information about the thelist mailing list