5

Having this fieldset:

<fieldset>
    <legend>[*death]</legend>
    <select name=death  style="width: 120px">
        <option value=Dead>[*died]
        <option value=NotDead>[*alive]
        <option value="" selected>-
    </select>
</fieldset>

i want to set the [2].value to "-".

i have tried without any success:

document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';  

Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?

Thanks

[EDIT] of course, appropriate fieldset is:

<fieldset>
  <legend>[*death]</legend>
    <select name="death"  style="width: 120px">
      <option value="Dead">[*died]</option>
      <option value="NotDead">[*alive]</option>
      <option value="" selected>-</option>
    </select>
</fieldset>

thanks.

moribvndvs
  • 42,191
  • 11
  • 135
  • 149
volvox
  • 1,194
  • 6
  • 22
  • 29

5 Answers5

9

It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?

document.getElementsByName('death')[0].selectedIndex = 2;

Or, are you asking to change the value of option at index 2?

var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
2

You need to manipulate the selected property of your select object, try

document.getElementsByName('death')[0].selectedIndex = 1;

In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".

Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:

<fieldset>
  <legend>[*death]</legend>
    <select name="death"  style="width: 120px">
      <option value="Dead">[*died]</option>
      <option value="NotDead">[*alive]</option>
      <option value="" selected>-</option>
    </select>
</fieldset>
brabster
  • 42,504
  • 27
  • 146
  • 186
1

you can do this using jQuery... it's easy...

j("#death").val(2)
Ju Nogueira
  • 8,435
  • 2
  • 29
  • 33
0

document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...

kevingessner
  • 18,559
  • 5
  • 43
  • 63
0

Here's an alert example of how to access your specific option values with getElementsByName

alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead