tags:

views:

342

answers:

4

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.

+1  A: 

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
Thanks for the fixing. Your suggestion is also fine.
volvox
+2  A: 

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 = '-';
HackedByChinese
document.getElementsByName('death')[0].selectedIndex = 2; is fine. Thanks
volvox
A: 

document.getElementsByName('death')[2] returns the second 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 second option: document.getElementsByName('death')[0].options[2].value = ...

kevingessner
+1  A: 

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

j("#death").val(2)
j.
using a javascript framework is definitely better. i'd like to point out, however, that his HTML is using a name and not an ID.
HackedByChinese
my mistake. tks.
j.
How if no ID (or, i could actually add an ID)
volvox