Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5974
  • Last Modified:

Set selected index in drop down select

Hi

I have got a dropdown select (of countries).  

As part of my page generation, I want to set the selected index of a dropdown via my javascript.

So, say in my dropdown list (of EVERY country) I wanted to select the United Kingdom, its value would be set to "UK" - here is a quick example.

<select name="dropdown">
<option value="CH">China</option>
<option value="UK">United Kingdom</option>
</select>

So in my Javascript, i want to tell it to select "UK".   But not index number [1] if you understand what I mean, I want to use the actual value.

Many thanks

Daz
0
daz_oldham
Asked:
daz_oldham
  • 2
  • 2
  • 2
  • +1
1 Solution
 
bobbit31Commented:
<script language=javascript>
  function setSelectIndex(sel, val) {
     for (i=0;i<sel.options.length;i++) {
        if (sel.options[i].value == val) {
           sel.selectedIndex = i;
           break;
        }
     }
  }
</script>

<body onload="setSelectIndex(document.Form1.dropdown, 'UK');">
0
 
daz_oldhamAuthor Commented:
Hey bobbit, thanks for that :)

is there no way to automatically select that value?

I should imagine if the list of countries is about 30 or so, maybe even more - then that is going to take a long time to execute on the clients side?

Thanks

Daz
0
 
bobbit31Commented:
it won't take long... 30 is nothing.

BUT, if you want to do it another way:

<body onload="document.Form1.dropdown.value = 'UK';">

though i'm not sure that it is supported by all browsers

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jaysolomonCommented:
<body onload="document.forms[0].dropdown.selectedIndex = 1">
<form name="form1" method="post" action="">
<select name="dropdown">
<option value="CH">China</option>
<option value="UK">United Kingdom</option>
</select>
</form>
</body>
0
 
knightEknightCommented:
or just use the SELECTED keyword in the option:

<option value="UK" SELECTED>United Kingdom</option>
0
 
jaysolomonCommented:
true
0
 
daz_oldhamAuthor Commented:
Thanks guys for the help
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now