Reputation: 1390
I have a form which looks like below, where the user can select multiple options. I am trying to do the same thing (when the page regenerates) from javascript. I am not sure where I am going wrong. Could someone correct me?
<form name="myForm">
<select name="numSel[]" size="2" multiple="multiple">
<option value="ONE">ONE</option>
<option value="TWO">TWO</option>
<option value="THREE">THREE</option>
<option value="FOUR">FOUR</option>
</select>
</form>
This is the javascript code that I am trying (trying to select ONE and THREE):
document.myForm.numSel.options[1].selected = true;
document.myForm.numSel.options[3].selected = true;
Any ideas?
Edit: Syntax corrected (not actually in the code). I intend to generate the javascript statements in PHP and the numSel[] is needed for it to work. So, in this scenario, how do I change the code?
Thanks.
Upvotes: 1
Views: 1711
Reputation: 1279
Change your JS code this way:
document.forms["myForm"].elements["numSel[]"].options[1].selected = true;
document.forms["myForm"].elements["numSel[]"].options[3].selected = true;
And correct the closing tag </select>
.
Upvotes: 2
Reputation: 24334
name="numSel[]"
does not match the name in your script. Change that to just numSel
and it works:
<select name="numSel" size="2" multiple="multiple">
.. or alternatively target it by the name "numSel[]"
document.myForm["numSel[]"].options[1].selected = true;
document.myForm["numSel[]"].options[3].selected = true;
Upvotes: 2