Update a SELECT list: set option.selected=true without throwing an **undefined** error.

Posted on 2005-04-29
Last Modified: 2011-04-14
I have a hidden field which contains a value.  I have a SELECT/OPTION list that has no selected options.  After the select is written to the browser, I want to make to option, corresponding to the hidden value to become selected.  The JavaScript below consistantly throws an undefined error when I execute the line to set the correct option's selected value to true.  Funny enough, if I trap the error with a try .. catch block, the assignment works (cross browser).  

Question: >How can I set the correct option to selected without the try .. catch block, without the error and without putting the options into an array and rebuilding the SELECT dynamically with JavaScript?

    <select id="country" name="country" size="1">
          <option value="AF">AFGHANISTAN</option>
            <option value="AL">ALBANIA</option>
            <option value="AD">ANDORRA</option>
            <option value="AO">ANGOLA</option>
            <option value="AI">ANGUILLA</option>
            <option value="AG">ANTIGUA</option>
            <option value="VE">VENEZUELA</option>
            <option value="VN">VIETNAM</option>
            <option value="WF">WALLIS AND FUTUNA ISLANDS</option>
            <option value="YE">YEMEN</option>
            <option value="ZM">ZAMBIA</option>
            <option value="ZW">ZIMBABWE</option>
    <input type="hidden" id="cSave" name="cSave" value="VN">
<script language="javascript" type="text/javascript">
if (document.getElementById('cSave').value!='') {
      for (var idx=0;idx<document.getElementById('country').options.length;idx++) {
            if (document.getElementById('cSave').value==document.getElementById('country').options[idx].value) {
                        // The next line throws an undefined error.
                        // if the error is trapped with try .. catch, the option is selected
                        // as desired.  I can live with the try .. catch since I get the
                        // action I need, but I would prefer to get the desired action
                        // without the try .. catch block, if possible.

                        // THIS WORKS BUT I WANT TO GET RID OF THE TRY .. CATCH
                        //try {
                  //      document.getElementById('country').options[idx].selected=true;
                  //catch(e) {
                  //      if(e.error!=undefined) {
                        //           alert(e.error);
                  //      }

Question by:rdivilbiss
    LVL 29

    Author Comment

    TYPO: I want to make the option corresponding to the hidden value become selected.
    LVL 32

    Accepted Solution

    While you are already selecting the index with this statement:


    what is the need for ...selected=true; ?
    LVL 29

    Author Comment

    You got me?

    I probably was having another problem, and decided I needed the selected=true.  However, it does work without the that will do just fine.


    (Still would like to know why the other threw an error, it should be assignable.)

    LVL 29

    Author Comment

    Seems to be one or the other.  If I use the selected=true without the previous selectedIndex = idx no error, If I use selectedIdx = idx without selected=true it also works no error.

    The undefined error must be related to using both, although I don;t see why you couldn't set the selected option as many times as you want, but hey my problem is solved, and when you get tired of playing with it, it is time to hand out poinx.

    I am supposed to be in bed and that's where I'm headed.  All the best to you and yours in the coming month.

    LVL 32

    Expert Comment

    Glad the problem is solved.

    To check a form variable (or an id) in HTML, you can boolean check if the field/value exists or not. For example:

     // do something.
     // something else.

    However, try..catch is not something to be ignored. Its the nice/better way of cathcing errors. :=)

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
    Article by: DanRollins
    This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (, we'll extend the program by adding a depth-…
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now