1

i'm sort of new to jQuery, i need to create URLs based on a few things, first, 1 dropdown menu where i can select a region, depending on the region, the second dropdown needs to display countries in that region, each option of the second dropdown has a value that will be part of the URL, in this case, the language code and the country code, then selecting a list of links where each href attribute will be the last part of the URL, and show the final URL in a text or a paragraph

<select name="region" id="region">
    <option value="none">Select a Region...</option>
    <option value="europe">Europe</option>
    <option value="asia">Asia</option>
    <option value="americas">Americas</option>
</select>

<select name="countries" id="country">
    <option value="none">Select a Country...</option>
    <option value="africa/en" class="europe">Africa - English</option>
    <option value="africa/fr" class="europe">Africa - French</option>
    <option value="at/de" class="europe">Austria</option>
    <option value="by/ru" class="europe">Belarus</option>
    <option value="be/nl" class="europe">Belgium - Dutch</option>
    <option value="bg/bg" class="europe">Bulgaria</option>
    <option value="au/en" class="asia">Australia</option>
    <option value="cn/zh" class="asia">China</option>
    <option value="hk/zh" class="asia">Hong Kong - Chinese</option>
    <option value="hk/en" class="asia">Hong Kong - English</option>
    <option value="in/en" class="asia">India</option>
    <option value="id/en" class="asia">Indonesia</option>
    <option value="ca/fr" class="americas">Canada</option>
    <option value="us/en" class="americas">US</option>
</select>

<div id="categories">
<ul style="float:left;width:230px;">
    <li><a href="/shop/clothes/index.html" target="_blank">Clothes</a></li>
    <li><a href="/shop/food/index.html" target="_blank">Food</a></li>
    <li><a href="/shop/electronics/index.html" target="_blank">Electronics</a></li>
    <li><a href="/shop/games/index.html" target="_blank">Video Games</a></li>
</ul>

clicking on the li items should return the final URL, for example, selectin Americas, the second dropdown should only show Canada and US, and clicking on Clothes, a paragraph should appear and have "us/en/shop/clothes/index.html" it would be great to have the actual page below these selections, i hope i was clear enough, thanks in advance.

Uls Cortez
  • 15
  • 2
  • No need to do this with JQuery, you could do it server side. Is there a reason JS is required? – EternalHour Mar 18 '15 at 23:33
  • Do you know how to bind to events using jQuery? Also, can you construct a CSS selector that will find the correct options of the second dropdown? – Patrick McLaren Mar 18 '15 at 23:33
  • Not sure what you want to append the country value to but this shoudl get you part way there: http://jsfiddle.net/20okpsa6/ – prodigitalson Mar 18 '15 at 23:47

2 Answers2

0

First, you'll need to watch for a change in the country dropdown, then change the second options accordingly.

$('select[name="region"]').change(function (event) {
  var countrySelect = $('select[name="countries"]');
  var region = event.target.value;

  // Reset the country select
  countrySelect[0].selectedIndex = 0;

  // Enable/disable the country select
  countrySelect.prop('disabled', region === 'none');

  // Show/hide the corresponding countries
  countrySelect.find('option').each(function (idx, elm) {
    if (elm.className.indexOf(region) > -1) {
      $(elm).show();
    } else {
      $(elm).hide();
    }
  });
});

Then, you'll need to adjust the links

$('#categories a').each(function (idx, elm) {
  $(elm).click(function (event) {
    event.preventDefault();

    var countrySelect = $('select[name="countries"]')[0];
    if (countrySelect.selectedIndex <= 0) {
      alert('Please select a country first!');
    } else {
      // Change page to adjusted url
      window.location = countrySelect.value + $(elm).attr('href');
    }
  });
});

See JSFiddle.

Patrick McLaren
  • 978
  • 10
  • 22
0

I would create a plugin for something like this so that it would be reusable elsewhere:

// option filtering plugin courtesy of Paolo Bergantino
// http://stackoverflow.com/questions/877328/jquery-disable-select-options-based-on-radio-selected-need-support-for-all-brow/878331#878331


// "trigger" is a selector for the element that will trigger the filter
// "seetings" are options for the plgin, in this case we use  {first:'none', dataAttr:'region'} 
jQuery.fn.filterOn = function(trigger,settings) {
    return this.each(function() {
        var first={};
        var select = this;
        var options = [];
          // get all of the orgiginal options 
          // if first option's region is set to our settings.first value
          // set it's info as our default selection/first option
          $(select).find('option').each(function (i, e) {
              if( i == 0 && $(this).data(settings.dataAttr) === settings.first){ 
                  first={
                    value: $(this).val(),
                    text: $(this).text(),
                    region: $(this).data(settings.dataAttr)
                  }
              }
              else{
                // get each option's value, text, and region ( region being: data-region="asia" for example )
                options.push({
                    value: $(this).val(),
                    text: $(this).text(),
                    region: $(this).data(settings.dataAttr)
                });
              }
        });
        // empty the select, store the options in a data attribute on the select, then load just the first, default option
        $(select).empty().data('options', options).data('first', first).append( $('<option>').text(first.text).val(first.value).data(settings.dataAttr, first.region) );
        // listen for changes from our trigger element
        $(trigger).change(function () {
            // if selected default option, filter the select to it's default 
            // first option's text must contain "..." 
            // not other option's text should contain "..."
            if ($(this).val() === settings.first){ 
                $(select).empty().append($('<option>').text(first.text).val(first.value).data(settings.dataAttr, first.region));
            } 
   else {
                // if selected a real option, clear the select box's options
                // then get the second select's original options from it's data attribute                
                var options = $(select).empty().data('options');
                // get the region form the trigger element's value
                var selectedRegion = $(this).val();
                // loop through each of the original options
                $.each(options, function (i) {
                    var option = options[i];
                     // if the option's region is the same as the selected region
                     // or if the option's region is equal to 'none' (our defualt option), add it back to the select element
                    if (selectedRegion === option.region || option.region === settings.first) {
                        $(select).append( $('<option>').text(option.text).val(option.value).data( settings.dataAttr, option.region) );
                    }
                });
      }
        });
    });

};


$(function() {
    // call our plugin
    // {first:'none',dataAttr:'region'}  are settings for the plugin
    // first:'none' tells the plugin what the value of the first option should be so it can always find in int the group later 
    // dataAttr:'region' tells the plugin we want to filter the options by their 'data-region' value
    $('#country').filterOn('#region', {first:'none',dataAttr:'region'} );
    
    // when clicking link, add current selection to url then display it
    $('#categories li a').click(function(e){
        e.preventDefault();
        var h = $(this).attr('href');
        var c = $('#country').val();
        var myUrl = c !== 'none' ? c + h : 'Please select a country!';
        $('#showlinks').html(myUrl);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="region" id="region">
    <option value="none">Select a Region...</option>
    <option value="europe">Europe</option>
    <option value="asia">Asia</option>
    <option value="americas">Americas</option>
</select>

<select name="countries" id="country">
    <option value="none" data-region="none">Select a Country...</option>
    <option value="africa/en" data-region="europe">Africa - English</option>
    <option value="africa/fr" data-region="europe">Africa - French</option>
    <option value="at/de" data-region="europe">Austria</option>
    <option value="by/ru" data-region="europe">Belarus</option>
    <option value="be/nl" data-region="europe">Belgium - Dutch</option>
    <option value="bg/bg" data-region="europe">Bulgaria</option>
    <option value="au/en" data-region="asia">Australia</option>
    <option value="cn/zh" data-region="asia">China</option>
    <option value="hk/zh" data-region="asia">Hong Kong - Chinese</option>
    <option value="hk/en" data-region="asia">Hong Kong - English</option>
    <option value="in/en" data-region="asia">India</option>
    <option value="id/en" data-region="asia">Indonesia</option>
    <option value="ca/fr" data-region="americas">Canada</option>
    <option value="us/en" data-region="americas">US</option>
</select>

<div id="categories">
<ul style="float:left;width:230px;">
    <li><a href="/shop/clothes/index.html" target="_blank">Clothes</a></li>
    <li><a href="/shop/food/index.html" target="_blank">Food</a></li>
    <li><a href="/shop/electronics/index.html" target="_blank">Electronics</a></li>
    <li><a href="/shop/games/index.html" target="_blank">Video Games</a></li>
</ul>
</div>
<br>
<p id="showlinks"></p>
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • thanks! it is very usefull, i'll implement it in the ongoing project and hope i don't mess anything else :p – Uls Cortez Mar 19 '15 at 17:35
  • i would like to see if this could be addapted so if i select another country, the current URL changes automatically, for example, if im already in "electronics" for United States and then i select Canada, how can the current URL updates to be for "electronics" for Canada without having to select electronics again? thanks @delightedd0d – Uls Cortez May 27 '15 at 22:13
  • @UlsCortez Im not sure I follow. In your original question, you select a region which filters a list of countries. Then you select a country which appends its value to the links. Can you walk me through what needs to happen now step by step? – Wesley Smith May 30 '15 at 14:20