Reputation: 45
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 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.
Upvotes: 2
Views: 4623
Reputation: 707786
You have these issues:
You're overwriting the name of your function and should use a local variable of a different name.
You're reference a single element form getElementsByName when it returns an array.
Try this:
<script>
function setexample(){
var item = document.getElementById("exampleID");
var val = item.options[item.selectedIndex].value;
var list = document.getElementsByName("exampleform");
for (var i = 0; i < list.lenth; i++) {
list[i].value = val;
}
}
</script>
Upvotes: 0
Reputation: 147453
In your code:
> function setexample(){
> setexample = document...
The assignment to setexample overwrites the existing value (which is the function setexample). Declare the variable inside the function:
var setexample = document...
For the rest, see nnnnnn's answer.
Upvotes: 1
Reputation: 150080
The getElementsByName()
method returns a list of elements, so you can't just directly set the value
property 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):
var els = document.getElementsByName("exampleform");
for(var i = 0; i < els.length; i++)
els[i].value = setexample;
For the rest, see RobG's answer.
Upvotes: 0