user342391
user342391

Reputation: 7827

Creating a menu to switch languages on site

I have a dropdown menu on my site that I want to use to switch between the different languages:

 <select onChange="if(this.selectedIndex!=0) self.location=this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage">
    <option value="http://demo.com/?lang=en">
                English (International)</option>    
        <option value="http://demo.com/?lang=es">
                Español (European)</option>
                     </select>

How can I get the above menu to display which language is currently showing. Is there someway of showing an active state. Site is using php.

Thanks in advance.

Upvotes: 1

Views: 2310

Answers (4)

Alex Kolarski
Alex Kolarski

Reputation: 3425

If you are using PHP I'll suggest you to refector the code like this, because that way you can easily add new language, without writing HTML code or additional javascript. You can use the $langs array to hold your current set of languages.

I also made $server_location variable that contains the current page URL. That way you will not have problems when you move you page to different servers and domains or if you rename your page.

    <?  
        $langs = array('en' => 'English (International)',
                       'es' => 'Español (European)'
                      );

        function is_current_language($code)
        { 
                 return ($code == $_GET['lang'])? 'selected="selected"': "";
        }

        $server_location= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];

    ?>

    <select onchange="if(this.selectedIndex!=0) self.location='<?=$server_location;?>?lang='+this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage">

       <? foreach($langs as $code => $lang): ?>
          <option <?= is_current_language($code); ?> value="<?= $code; ?>">
             <?= $lang; ?>
          </option>
       <? endforeach; ?>

    </select>

Upvotes: 0

m4rc
m4rc

Reputation: 3006

You could use Google Translate Tools... will save you a whole lot of work in the long run.

http://translate.google.com/translate_tools

Upvotes: 0

aorcsik
aorcsik

Reputation: 15552

Using PHP this, is a go. (I changed the selection a bit.)

<select onChange="if(this.selectedIndex!=0) self.location='http://demo.com/?lang='+this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage">
    <option <?php if ($_GET['lang'] == "en") { ?>selected="selected"<?php } ?> value="en">English (International)</option>    
    <option <?php if ($_GET['lang'] == "es") { ?>selected="selected"<?php } ?> value="es">Español (European)</option>
</select>

Hope this helps!

Upvotes: 2

swishmiller
swishmiller

Reputation: 86

Add selected="selected" to your option. Take a look: http://jsfiddle.net/tW2jm/

<option selected="selected" value="http://demo.com/?lang=en">

Upvotes: 1

Related Questions