1

I'm trying to manipulate dropdown lists through javascript, but I seem to get this code every time I click a button:

TypeError: objDropDownMenu.options is undefined

objDropDownMenu.options[1].selected = true;

Here is my code:

<FORM NAME="myform" ACTION="" METHOD="GET">
<SELECT class="select diff_data" style="WIDTH: 165px" name=CarPick>
<OPTION value=1>Audi</OPTION>
<OPTION value=2>BMW</OPTION>
<OPTION value=3>Mercedes</OPTION>
</SELECT>

<INPUT TYPE="button" NAME="button2" Value="Write" onClick="writeText(this.form)">
</FORM>

<SCRIPT LANGUAGE="JavaScript">
var objDropDownMenu = document.getElementsByName("CarPick");



function writeText (form) {
    objDropDownMenu.options[30].selected = true;
}
</SCRIPT>

Anyu idea why? Thanks!

2
  • And where is ProcStage defined? Commented Feb 4, 2013 at 14:58
  • Sorry, I forgot to change it in my code :) Commented Feb 4, 2013 at 16:12

2 Answers 2

3

getElementsByName always returns an array of objects.

So you have to use: objDropDownMenu[0].options[30].selected = true

A better way to approach this is to set an ID for your select and then use document.getElementById('yourid') which will always return just one object (since the ID should always be unique in a HTML document).

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure, if your code is just an example, but if not, there many unmatching names. Lets fix that:

<FORM NAME="myform" ACTION="" METHOD="GET">
<SELECT class="select diff_data" style="WIDTH: 165px" name="CarPick">
<OPTION value="1">Audi</OPTION>
<OPTION value=2>BMW</OPTION>
<OPTION value=3>Mercedes</OPTION>
</SELECT>

<INPUT TYPE="button" NAME="button2" Value="Write" onClick="writeText(this.form)">
</FORM>

<SCRIPT LANGUAGE="JavaScript">
var objDropDownMenu = document.getElementsByName("CarPick")[0];   //It is get elementS - all alements with that name are returned



function writeText (form) {
    objDropDownMenu.options[2].selected = true;  //Here I wonder if 30th entry exists, 2 surelly does
}
</SCRIPT>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.