...

View Full Version : Select US State (in a var) from the populated state dropdown box



pa2stepper
10-24-2003, 08:55 PM
I thought I had this solved from someone's else's question so I tried the code suggested. I got an error saying the property or method is not supported.

I have variable containing a state abbreviation.
I'm trying to get my already-populated drop-down to select the
state contained in the variable

document.editForm.state.options[document.editForm.state.selectedIndex].value=s;

How hard could this be - the state dropdown is already populated and will definitely find the 2-letter abbrev value - isn't there a one-liner to set it?

Thank you,
Mary:rolleyes:

COBOLdinosaur
10-25-2003, 08:22 PM
document.editForm.state.options[document.editForm.state.selectedIndex].value=s;

Would change the avlue of the currently selected option. I think you want somthing like:

var obj = document.forms['editForm].state;
for (i=0;i<obj.options.length;i++)
{
if (s==obj.options[i].value)
{
obj.options[i].selected=true;
obj.selectedIndex=i;
return;
}
}
alert('Stat not found');


The select options would have the abbreviation as their values:

<select name="state">
<option value="VA">Virgina</option>
<option value="MI">Michigan</option>
<option value="CO">Colorado</option>

Etc....

pa2stepper
10-26-2003, 01:16 AM
Hi - thanks for the reply. I tried both suggestions and neither worked. I can't figure this out.

I retrieved the state value from the database, "PA" for example, in a variable and simply want to select/highlight "PA" in the state drop down - the abbrev values are already in there and will always find its match. The state drop down looks like this.

<select name="state">
<option value=""></option>
<OPTION VALUE="AB">AB
<OPTION VALUE="AK">AK
<OPTION VALUE="AL">AL

Any further ideas come to mind?
Thanks!
Mary

pa2stepper
10-26-2003, 01:29 AM
Sorry about that CDino - it surely did work. I had to remove the return as it was causing an error (outside of function?) and then I removed the alert and now it works beautifully. I suspect, it's not working as efficiently without the return, probably selecting the match, then continuing down the line, but that's okay for now. Thanks a million for your help with this, CDino!
Best,
Mary

COBOLdinosaur
10-26-2003, 10:51 PM
You are right about it being inefficient. The return should be break:

var obj = document.forms['editForm].state;
for (i=0;i<obj.options.length;i++)
{
if (s==obj.options[i].value)
{
obj.options[i].selected=true;
obj.selectedIndex=i;
break;
}
}

sorry about that.:o

adios
10-27-2003, 03:38 AM
This is even more efficient - particularly for long lists:

http://www.oreillynet.com/pub/a/javascript/excerpt/JS&DHTMLCkbk_chap8/index2.html



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum