I have various forms on a page, and a PHP-generated select on the top of the page.
What I want to do is:
- The user selects an option from the form.
- The value of the option is put into all of the inputs with a specific name.
- The user can select another option, and the value of that option would replace the old value of the input.
The code I have so far (that doesn’t work):
It doesn’t work as in the onChange only fires the first time you select an option, and the values of the inputs aren’t updated to the chosen option’s value.
The select: (It can have more or less than three options, depending on the user.)
<select name="example" onchange="setexample()" id="exampleID">
<option value="1">Default Example</option>
<option value="12">User-created Example #2</option>
<option value="8">User-created Example #1</option>
</select>
This is part of one of the forms around the page:
<form action="[URL]" method="get">
<input type="hidden" name="exampleform" id="example1" value="">
// Other inputs //
</form>
JavaScript:
<script>
function setexample(){
setexample = document.getElementById("exampleID").options[document.getElementById("exampleID").selectedIndex].value;
document.getElementsByName("exampleform").value = setexample;
}
</script>
I don’t want to use jQuery. This is just JavaScript.
Thank you in advance.
The
getElementsByName()method returns a list of elements, so you can’t just directly set thevalueproperty that belongs to the individual elements in the list. You need to loop through the list (it’s an HTMLCollection but for this purpose you can treat it like an array):For the rest, see RobG’s answer.