volvox volvox - 2 months ago 8
Javascript Question

Set option value with getElementsByName()

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.

Answer

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 = '-';
Comments