Search code examples
javascriptphphtmlsessionselected

Get an option ''selected'' based on a $_Session value


i am having a platform where every user creates a profile and has to insert his personal info into a DB.One of this is the nationality ,that is being inserted by an HTML drop list (with 100+ countries) when the user is creating his profile for the first time.

<select name="nationality" id="nationality" >
            <option value="0" label="Select a country ... " >Select a country ... </option>

When the user is loging back in to his profile , i want this dropdown list to have his nationality option marked as ''selected'' .

Nationality's value is into a $_Session , when all data are being selected when he logs in .

The most easy way to do this is by using a php code inside every option value like this

<option value="GR" label="Greece"   <?php if(($_SESSION['nationality'])=='GR') echo 'selected="selected"'; ?>>Greece</option>

But i can't do this with every option from a list of 300+ countries.I want this to be done by Javascript . I've tried many things but i can't sort it out Thank you in advance


Solution

  • If the session name of the country is the same as the value of the country from the selection list, this should work.

    <script>
    var country = '<?php echo $_SESSION["country"]; ?>';
    if(country !== ''){
        document.getElementById("nationality").value = country;
    }
    </script>