Set parameter value using getElementsByName () method

The presence of this set of fields:

<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 [2].value to "-" .

I tried without any success:

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

The same code is great for radio boxes, marked boxes or other inputs on the form. How to do this with selecting an option (which is not input)?

thanks

[EDIT], of course, a suitable set of fields:

 <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.

+4
source share
5 answers

It’s a little incomprehensible what you are asking. Are you just asking to make a choice in the selected index 2?

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

Or do you ask to change the value of the parameter in index 2?

 var d = document.getElementsByName('death')[0]; d.options[2].value = '-'; 
+7
source

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

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

In English, this means: "Set the selected option to the second option in the first element of the document with the name" death ".

Committing your HTML can make your javascript results more predictable. Close the tags, specify the values ​​of your attributes 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> 
+2
source

you can do it with jQuery ... it's easy ...

 j("#death").val(2) 
+1
source

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

0
source

Here's an example warning on how to access your specific parameter values ​​using getElementsByName

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

Source: https://habr.com/ru/post/1302516/


All Articles