Loop through dropdown list

Discussion in 'JavaScript' started by thedagda, Oct 11, 2006.

  1. #1
    I've got the following function that has me stumped. I'm pretty sure this is a simple problem, but I can't find a solution for it.

    Function:
    
    function selectit(formname,listname,num_options,val) {
    	if(val == '') {
    		return null;
    	} else {
    		for(i=0; i<num_options; i++) {
    			if(document.formname.listname.options[i].value==val) {
    				document.formname.listname.options[i].selected="selected";
    			}
    		}
    	}
    }
    
    Code (markup):
    Calling the function by:

    <script> selectit("form1","category",3,'cat_value'); </script> 
    Code (markup):
    The error that I'm getting is "document.formname has no properties." If I manually access the list: alert(document.form1.category.option[0].value); I get the correct value back.

    Also, if I alert formname and/or listname, I get the excpected values back. Any help will be greatly appreciated.

    Thanks,
     
    thedagda, Oct 11, 2006 IP
  2. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Need to see the form and its position relative to the script.
     
    Logic Ali, Oct 12, 2006 IP
  3. thedagda

    thedagda Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I actually ended up finding the solution. Instead of

    document.formname.listname.options
    Code (markup):
    It needed to be:
    document.forms[formname].elements[listname].options
    Code (markup):
    Hope this helps someone else with the same problem.
     
    thedagda, Oct 12, 2006 IP
  4. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Use window.forms for a cross-browser solution.

    Better yet avoid forms altogether, they are a clumsy and well outdated solution.
     
    penagate, Oct 13, 2006 IP
  5. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #5
    That would lead to a cross-browser failure.
     
    Logic Ali, Oct 13, 2006 IP
  6. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Argh, I read "frames" not forms.

    Ignore me.
     
    penagate, Oct 13, 2006 IP