select option by value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • theS70RM
    New Member
    • Jul 2007
    • 107

    select option by value

    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


    Code:
    function selectOptionByValue(selObj, value){
    	
    	for (options in selObj.options){
    		if (options.value == value){
    			options.selected = true;
    			break;
    	}
    		
    }

    Any help is much apprieciated1

    Thanks

    Andy
  • mrhoo
    Contributor
    • Jun 2006
    • 428

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


    Code:
    function selectOptionByValue(selObj, val){
    	var A= selObj.options, L= A.length;
    	while(L){
    		if (A[--L].value== val){
    			selObj.selectedIndex= L;
    			L= 0;
    		}
    	}
    }

    Comment

    • theS70RM
      New Member
      • Jul 2007
      • 107

      #3
      that works well,

      thanks for your help!

      Andy

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

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

        Comment

        Working...