1

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.

2
  • You have a syntax error </selectt> ?? Commented Aug 18, 2012 at 8:22
  • What do you exactly want to do? Select one and others get selected too? Be more specific Commented Aug 18, 2012 at 8:25

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

http://jsfiddle.net/m5GJW/

.. or alternatively target it by the name "numSel[]"

document.myForm["numSel[]"].options[1].selected =  true;
document.myForm["numSel[]"].options[3].selected =  true;​

http://jsfiddle.net/x3rGb/

2 Comments

Thanks. The 2nd solution worked and thanks for jsfiddle. Didn't know about it.
It's a great tool for testing javascript. Another similar/slightly more minimalist one, also useful, is jsbin.com. Mostly personal preference. (Strangely, though, jsbin is down right now)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.