1. Post #1
    Appeltaart's Avatar
    May 2007
    41 Posts
    Hi,

    I'm trying to get all the dropdowns in my form to select the option, with the value that is stored in the session, on page load.

    Right now I have this:

    Code:
    <script>
    window.addEvent('load', function() {
    
    <?php $select_array = array ('country', 'nationality', 'residence_permit', 'labor_permit', 'dag', 'maand', 'lunchbox');?>
    <?php foreach($select_array as $select_name){?>
        <?php if($_SESSION['ec_form_'.$select_name]){?>
            document.getElementsByName('<?php echo $select_name;?>')[0].selectedIndex= '<?php echo ($_SESSION['ec_form_'.$select_name]);?>';
        <?php }?>
    <?php }?>
    
    });
    </script>
    The problem with this code is that, if for example the value in the session is 150, it will select the 150th option in the dropdown and not the option with the value 150.

    Any idea's on how I can make it, that it selects the option with value 150?

    Thanks!

  2. Post #2
    Gold Member
    CBastard's Avatar
    April 2011
    410 Posts
    Can you not just add the selected attribute while generating the form option HTML itself, or are you unable to and have to do it with javascript?

  3. Post #3
    Appeltaart's Avatar
    May 2007
    41 Posts
    Can you not just add the selected attribute while generating the form option HTML itself, or are you unable to and have to do it with javascript?
    I can, but I want to do it like this so I can just copy past this in every form I have.
    And I have a lot of forms...

  4. Post #4
    Appeltaart's Avatar
    May 2007
    41 Posts
    Fixed!

    Code:
    <script>
    function selectOptionByValue(selObj, val){
        var A= selObj.options, L= A.length;
        while(L){
            if (A[--L].value== val){
                selObj.selectedIndex= L;
                L= 0;
            }
        }
    }
    
    window.addEvent('load', function() { 
    
    <?php $select_array = array ('country', 'nationality', 'residence_permit', 'labor_permit', 'dag', 'maand', 'lunchbox');?>
    <?php foreach($select_array as $select_name){?>
    	<?php if($_SESSION['ec_form_'.$select_name]){?>
    		selectOptionByValue(document.getElementsByName('<?php echo $select_name;?>')[0], '<?php echo ($_SESSION['ec_form_'.$select_name]);?>');
    	<?php }?>
    <?php }?>
    
    });
    </script>
    Thanks anyway! :)