By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,528 Members | 1,324 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,528 IT Pros & Developers. It's quick & easy.

select option by value

100+
P: 107
Hi Guys,

I've hit a wall, im trying to create a function to make an option in a <select> box selected when given its value, rather than its index. I cant seem to figure out how to loop through each value for each option.

This is what I have so far, but its not correct...
"selObj" is the <select> as an object


Expand|Select|Wrap|Line Numbers
  1. function selectOptionByValue(selObj, value){
  2.  
  3.     for (options in selObj.options){
  4.         if (options.value == value){
  5.             options.selected = true;
  6.             break;
  7.     }
  8.  
  9. }
  10.  

Any help is much apprieciated1

Thanks

Andy
May 21 '08 #1
Share this Question
Share on Google+
3 Replies


100+
P: 428
a select element has a property named 'options'-
use an indexed array to loop through the options.

If the select can only select 1 option, set the selectedIndex,
or you have to unset whatever was previously selected.


Expand|Select|Wrap|Line Numbers
  1. function selectOptionByValue(selObj, val){
  2.     var A= selObj.options, L= A.length;
  3.     while(L){
  4.         if (A[--L].value== val){
  5.             selObj.selectedIndex= L;
  6.             L= 0;
  7.         }
  8.     }
  9. }
May 21 '08 #2

100+
P: 107
that works well,

thanks for your help!

Andy
May 22 '08 #3

acoder
Expert Mod 15k+
P: 16,027
If you want a shortcut for single select object, just set its value property. Would work in at least Firefox/IE. mrhoo's method is obviously more robust and reliable though.
May 22 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.