0

I'm trying to change the options in a dropdown menu via a script - however nothing seems to happen. No errors either.

Here is the script:

javascript:
var objDropDownMenuName = document.getElementsByName("jjoprs")[0];
function writeText(form) {
    $(objDropDownMenuName.options[1]).selected = true;
    $(objDropDownMenuName).change();
}
writeText(this.form);

Here is the html of the form:

<select name='jjoprs' class='select2'>
                          <option value='NULL' selected> </option>
                          <option value='1060'>Sofi, Laco</option>
<option value='5160'>Vandrlka, Edo</option>
                             </select>

Thanks!

Edit: I am executing this script in IE8

2
  • Offtopic, but it would be better to give the select an ID and use document.getElementById('idHere'), its much more efficient to select things by ID Commented Sep 30, 2013 at 18:10
  • Unfortunately, it doesn't use an ID Commented Sep 30, 2013 at 18:10

2 Answers 2

1
function writeText(form) {
    objDropDownMenuName.options[1].selected = true;
    $(objDropDownMenuName).change();
}

The jQuery selector isnt needed to set an option selected


Since you have jQuery:

 function writeText(form) {
     $('select[name="jjoprs"]')
         .find('options:nth-child(2)').attr('selected',true)
         .closest('form').submit();
  }
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Martijn, if I don't use the .change function, the data is not saved in our system.
I've uncommented it again :) Thought you might've added it to make the select change.
Thanks, but nothing happens in this case either. @Kolink version works, however I can't get it to save.
jsfiddle.net/FadXB this does exactly what you ask :) I understand you want the form to submit afterwards?
Hey Martin.... your original script worked ;) The second one did not. The reason why your original script didn't work for me originally was because I forgot to execute writeText(this.form); at the end. Sorry for the trouble!
|
1

Try using the correct method:

var sel = document.getElementsByName('jjoprs')[0];
sel.selectedIndex = 1;

2 Comments

Thanks, however I get an error when I try to run this sel.change();
That's because sel is not a jQuery object.

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.