0

This has been one of the most frustrating online searches-for-an-answer-or-solution EVER! And I still haven't found anything out there that can perform this basic task - with that being said, this IS a search facility that's used very often all over the net ... so it comes as a surprise as to why there aren't many (any) demos / scripts for sale that can do this.

I want to have a search facility on my website whereby the user can select a country > province > town (3 drop downs).

Obviously if the user selects the USA (for example), the next dropdown populates / updates the provinces (states) relevant to USA and so forth with the next drop down.

I see a lot of people using ASP.net and AngularJS to perform this funtion but I am using neither languages and don't want to use them.

This guy here has developed a great solution for people who'd like their results to dynamically load up as they select items in the dropdowns - however this isn't what I want.

The Javascript and Json approach is where I like to go. Now this guy here made a great / simple solution for populating dropdowns (I am going to post the code for this script later on).

But with ALL of these demos and scripts online, they are ALL missing one thing - the SEARCH facility. It's great populating a dropdown to select correct items but that's half the job done and that's all it does.

I want the user to be able to click a SEARCH button AFTER the last item in a dropdown is selected and go to it's respective page (because isn't that what is supposed to be for? - Of course that also depends on the project at hand).

So lets take the code of the populated dropdown created by the guy in the second link:

HTML:

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <script src="js/jquery-1.8.1.min.js"></script>
    <script src="js/outils.js"></script>
</head>
<body>
    <div>
        <select id="Marque">
            <option value="0">Choix du marque</option>
            <option value="bmw">bmw</option>
            <option value="mercedes">mercedes</option>
            <option value="audi">audi</option>
            <option value="volswagen">volswagen</option>
        </select>
        <select id="Serie"></select>
    </div>
</body>

Javascript:

jQuery().ready(function(){
var tabMarque=[];
$.getJSON('file.json', function(data) {
    $.each(data, function(index, val) {
         tabMarque[index]=val;
    });
});

$('#Marque').change(function(event) {
    $marque=$(this).val();
    $htmlOption='<option value="0">Choix du serie</option>';
    if($marque!=0)
    {
        $.each(tabMarque[$marque], function(key, value) {
             $htmlOption+='<option 
value="'+value[0]+'">'+value[1]+'</option>';
        });
    }
    $('#Serie').html($htmlOption);
});
});

JSON:

{
"bmw":[
    ["1","serie 1"],
    ["2","serie 3"],
    ["3","serie 5"],
    ["4","serie 7"]
],
"mercedes":[
    ["6","class A"],
    ["7","class B"],
    ["8","class C"],
    ["9","class E"]
],
"audi":[
    ["10","a3"],
    ["11","a4"],
    ["12","a5"],
    ["13","a6"]
],
"volswagen":[
    ["14","polo"],
    ["15","golf"],
    ["16","cady"]
]
}

(Sorry, I'd like to put this on JSfiddle but there's json involved and I don't know where to put the json code).

So after the 3 dropdown boxes, I'd like to have a button saying "Go" or "Search" and once it's clicked it takes the user to the page of the last selected item.

EG (using the example code above - understand there's only 2 dropdowns in his code):

I select:

BMW

1 Series

... and then when I click "GO" - it take me to bmw-1-series.htm

How can this be done? Surely one could add urls to the items in the json file eg:

"bmw":[
    ["1","serie 1","http://www.example.com/bmw-1-series.htm"],
    ["2","serie 3","http://www.example.com/bmw-2-series.htm"],
    ["3","serie 5","http://www.example.com/bmw-3-series.htm"],
    ["4","serie 7","http://www.example.com/bmw-4-series.htm"]
 ],

and then when you click "GO", it will take you to the respective url. Obviously this needs extra code I can imagine to be able to grab the url of the selected item and take the user to that page (something I wouldn't know how to do)?

Is there a better way to do this?

UPDATE TO MAKE THIS CLEARER:

Go to CSS TRICKS DEMO

This is what I want (to be able to populate the dropdowns - this is the only thing the demo does) however if the user wants to search for Coffee's ... they would click on BEVERAGES > then choose COFFEE and then I'd like them to be able to click a button (just below the 2 dropdowns) saying SEARCH ... which will take them to a page with all the coffees listed on

10
  • So what's your actual question? How to add a search button and have it dynamically show/hide or disable/enable based on the state of the dropdown selections? Your question is titled "populating cascading dropdown" but that doesn't seem to actually be what you are asking? Commented Sep 29, 2015 at 18:09
  • With FUNCTIONAL SEARCH ... this is my question ... I want the selected items to be searchable. I don't know how to explain what I am asking better than my question above Commented Sep 29, 2015 at 18:11
  • By "functional search" do you mean "a working search capability"? Are you trying to search within the contents that are populated in the drop down, or are we just talking about the "search" button which in your example would jump to bmw-1-series.htm? That is not a search; it is much closer to a basic navigational menu. Commented Sep 29, 2015 at 18:24
  • Yes it's closer to a basic navigational menu however the difference is that you're pulling data from the json file otherwise if I put all the options and links in a typical NAV, then the NAV would be extremely long stuffed with links which ain't good for the user and SEO Commented Sep 29, 2015 at 18:33
  • If you are generally following along with the video you posted, you should be able to use that as a foundation. You can do one of two things with your links, either maintain your own datastructure (even a basic Object) to map between the value of the leaf node select items and then navigation destination, or add them directly as a data attribute when adding them to the menu. Then your button code can lookup the URL in whichever place you put it. In his line 15 (in the 'marque' handler) you could have $htmlOption+='<option value="'+val[0]+'" data-theurl="'+val[2]+'"...' if URL is in spot 2 Commented Sep 29, 2015 at 18:46

2 Answers 2

2

As you requested, I looked at the code and have corrected it. It can be found at:

http://plnkr.co/edit/RnCdfnrX0jy3RvmXjF56

Link-only answers are frowned upon in StackOverflow, so I will write a little more:

As I wrote in my original comment:

If you are generally following along with the video you posted, you should be able to use that as a foundation. You can do one of two things with your links, either maintain your own datastructure (even a basic Object) to map between the value of the leaf node select items and then navigation destination, or add them directly as a data attribute when adding them to the menu. Then your button code can lookup the URL in whichever place you put it. In his line 15 (in the 'marque' handler) you could have:

$htmlOption+='<option value="'+val[0]+'" data-theurl="'+val[2]+'"...'

if URL is in spot 2

Although C Fasolin took the code you pointed to and my advice and attempted to convert it to an answer, you are correct that the code provided in the answer has errors in it.

Since SO requires code for Plunkr links, I now also have to paste some code in here as well. This is the corrected JS code minus the silly number of alerts injected into the code (which I only bothered to comment out in the Plunkr, but removed here to be tidier). The HTML and JSON were fine and are also on the Plunkr. Note that the JSON data only contains URLs for the BMW examples so you will get a 404 when clicking "go" for other makes, ou marques, en français.

$(document).ready(function() {
  var tabMarque = [];
  $.getJSON('data.json', function(data) {
    $.each(data, function(index, val) {
      tabMarque[index] = val;
    });
  });

  $('#Marque').change(function(event) {
    var marque = $(this).val();
    var htmlOption = '<option value="0">Choix du serie</option>';
    if (marque !== '0') {
      var itemsMarque = tabMarque[marque];
      $.each(itemsMarque, function(key, value) {
        htmlOption += '<option value="' + value[0] + '" data-href="' + value[2] + '">' + value[1] + '</option>';
      });
    }
    $('#Serie').html(htmlOption);
  });

  $('#go').click(function() {
    var selected = $('#Serie').find('option:selected');
    var href = selected.data('href');
    window.location = href;
  });
});

Happy menuing!

Sign up to request clarification or add additional context in comments.

5 Comments

Ahhhh! Fantastic stuff dude! This is like GOLD! I'm telling you, you can't find this simple function out there! It's crazy! Not even in the Canyon! I honestly think you should Github this badass code! DO IT! Thanks a lot for all the effort you've put into this and getting back to me, I really appreciate it! One step at a time XD
@user3364730 - Thanks for the kind words - best of luck in adapting it to your specific needs. I'll think about generalizing it into a lib of some sort if I have some free time.
I'm back with a question regarding this cascade menu. What happens if I'd like to have a third select dropdown (at the moment there's only two)? I've been plonkering around on plunker to try find a logical solution and although I THINK my json is almost there, I know my js isn't correct ... check it out: plnkr.co/edit/OmjqoW2ApdoigM4nvGQU?p=preview (I hope that link shows my fork). In that fork and in the json file, you'll notice I've deleted everything else except BMW to make things simpler.
@user3364730 - I just saw this. I am about to turn in for the night. I'll take a real look at it in the morning when my eyes are fresh.
Highly appreciate it Barry! I'm not sure how you "saw" it because for some reason SO wasn't allowing me to link your name (@barry) in the comment ... but I guess I must be lucky. Nevertheless, I really appreciate your assistance
0

this solution work for me:

JAVASCRIPT:

$(document).ready(function(){
var tabMarque=[];

$.getJSON('file.data.txt', function (data) {

    alert(data);

    $.each(data, function(index, val) {
        tabMarque[index]=val;
    });
});

$('#Marque').change(function(event) {
    alert('Marque_change');
    var marque=$(this).val();
    alert(marque);

    var htmlOption='<option value="0">Choix du serie</option>';
    if(marque!="0")
    {

        var itemsMarque = tabMarque[marque];
        alert(JSON.stringify(itemsMarque));
        $.each(itemsMarque, function (key, value) {
            //alert("k=" + key + " v=" + JSON.stringify(value));
            htmlOption+='<option value="'+value[0]+'" data-href="'+value[2]+'">'+value[1]+'</option>';
        });
    }
    $('#Serie').html(htmlOption);
});

$('#go').click(function () {
    alert('go_click');
    var selected = $('#Serie').find('option:selected');
    var href = selected.data('href');
    alert('goto:'+href);
});

});

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <script src="js/jquery-1.8.1.min.js"></script>
    <script src="js/outils.js"></script>
</head>
<body>
    <div>
        <select id="Marque">
            <option value="0">Choix du marque</option>
            <option value="bmw">bmw</option>
            <option value="mercedes">mercedes</option>
            <option value="audi">audi</option>
            <option value="volswagen">volswagen</option>
        </select>
        <select id="Serie"></select>
        <input type="button"  id="go" value="Go!" />
    </div>
</body>
</html>

JSON:

{
"bmw":[
    ["1","serie 1","http://www.example.com/bmw-1-series.htm"],
    ["2","serie 3","http://www.example.com/bmw-2-series.htm"],
    ["3","serie 5","http://www.example.com/bmw-3-series.htm"],
    ["4","serie 7","http://www.example.com/bmw-4-series.htm"]
],
"mercedes":[
    ["6","class A"],
    ["7","class B"],
    ["8","class C"],
    ["9","class E"]
],
"audi":[
    ["10","a3"],
    ["11","a4"],
    ["12","a5"],
    ["13","a6"]
],
"volswagen":[
    ["14","polo"],
    ["15","golf"],
    ["16","cady"]
]
}

3 Comments

Thanks buddy for the code - I really appreciate it! I've tested it out and the 2nd dropdown box isn't loading any items (it's blank). Must I test it live on a server in order for it to work? Also, I see in your javascript: $.getJSON('file.data.txt', function (data) { ... must the json code be in a .txt file and not a .json?
the file contain json data, the extension of file must be recognized from application server otherwise return 404 error.
I've copied your code exactly and it doesn't work. The second dropdown box is empty / doesn't load or have items to choose ... and I've tested it on a server... Have you tried your solution? How did you get it to work for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.