Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set option value with getElementsByName()

Tags:

javascript

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.

like image 307
volvox Avatar asked Feb 26 '10 18:02

volvox


People also ask

How do you get getElementsByName value?

How it works: First, select the submit button by its id btnRate using the getElementById() method. Second, listen to the click event of the submit button. Third, get all the radio buttons using the getElementsByName() and show the selected value in the output element.

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


1 Answers

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 = '-';
like image 61
moribvndvs Avatar answered Oct 07 '22 01:10

moribvndvs