Chris Cather Chris Cather - 5 months ago 25
jQuery Question

Language Dropdown Based on Page

I have a simple Select box with language Options. Each option will load a different page based on the selected language. The navigation works, but I need the default selected item to be based on the page's ID, which is set using PHP.

I have jQuery 1.12 already loading on the page, so that library can be used if needed.

<?php
$body_id = "en";
?>

<form id="language" method="post">
<select class="language" onchange="window.location.href=this.value">
<option selected="selected">LANGUAGE</option>
<option value="index-da.php">DANSK</option>
<option value="index-de.php">DEUTSCH</option>
<option value="index.php">ENGLISH</option>
<option value="index-es.php">ESPA&#209;OL</option>
<option value="index-fr.php">FRAN&#199;AIS</option>
<option value="index-it.php">ITALIANO</option>
<option value="index-pl.php">POLSKI</option>
</select>
</form>

Answer

Use filter to get target option element and apply condition based on the value of the option

var $body_id = "en";
var filtered = $('.language').find('option').filter(function() {
  return this.value.split('.')[0].split('-')[1] == $body_id;
});
if (filtered.length) {
  filtered.prop('selected', true);
} else {
  $('.language').find('option[value="index.php"]').prop('selected', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="language" method="post">
  <select class="language" onchange="window.location.href=this.value">
    <option selected="selected">LANGUAGE</option>
    <option value="index-da.php">DANSK</option>
    <option value="index-de.php">DEUTSCH</option>
    <option value="index.php">ENGLISH</option>
    <option value="index-es.php">ESPA&#209;OL</option>
    <option value="index-fr.php">FRAN&#199;AIS</option>
    <option value="index-it.php">ITALIANO</option>
    <option value="index-pl.php">POLSKI</option>
  </select>
</form>

For other language

var $body_id = "da";
var filtered = $('.language').find('option').filter(function() {
  return this.value.split('.')[0].split('-')[1] == $body_id;
});
if (filtered.length) {
  filtered.prop('selected', true);
} else {
  $('.language').find('option[value="index.php"]').prop('selected', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="language" method="post">
  <select class="language" onchange="window.location.href=this.value">
    <option selected="selected">LANGUAGE</option>
    <option value="index-da.php">DANSK</option>
    <option value="index-de.php">DEUTSCH</option>
    <option value="index.php">ENGLISH</option>
    <option value="index-es.php">ESPA&#209;OL</option>
    <option value="index-fr.php">FRAN&#199;AIS</option>
    <option value="index-it.php">ITALIANO</option>
    <option value="index-pl.php">POLSKI</option>
  </select>
</form>