0

Hi I have a select menu (well three) - and the 2nd two populate based on the choices of the first one, a 1,2,3 selector... - I really need to sort the 2nd and 3rd ones except for the first row... and I've seen some snippets on how to sort it... but I cannot figure out how to get it to work since the code is fired on page load, and the menu isn't populated until a choice is made from first.

any help is greatly appreciated.

I think what I need is this, but I cant figure out how to make it work

How to trigger jQuery change event in code

Community
  • 1
  • 1
CVP
  • 11
  • 1
  • 3

1 Answers1

0

JSFIDDLE

If I understood correctly, this should point you in the right direction for dynamically changing select menu options based on the previous selection.

Markup:

<select id="select1">
    <option disabled selected>Please select an option.</option>
    <option>Option One</option>
    <option>Option Two</option>
</select>

<select id="select2">
    <option>g</option>
    <option>b</option>
    <option>j</option>
    <option>c</option>
    <option>d</option>
    <option>h</option>
    <option>e</option>
    <option>h</option>
    <option>a</option>
    <option>i</option>
    <option>f</option>
</select>

jQuery:

$(document).on('change', '#select1', function(){
    var options = $('#select2 option');
    var arr = options.map(function(_, o) {
        return {
            t: $(o).text(),
            v: o.value
        };
    }).get();
    arr.sort(function(o1, o2) {
        return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
    });
    options.each(function(i, o) {
        console.log(i);
        o.value = arr[i].v;
        $(o).text(arr[i].t);
    });
});

Hope this helps!

EDIT: Changed so that the first menu triggers a sorting of the second menu. Updated the fiddle as well.

wrxsti
  • 3,434
  • 1
  • 18
  • 30
  • thanks, that sure looks like it'll work for the "Change" function, what I'm trying to do is to sort the results of the dropdown, but there's nothing in it, until something is chosen from first, so there's nothing to sort :/ – CVP Dec 10 '13 at 22:48
  • Do you know what the secondary menus options will be? – wrxsti Dec 10 '13 at 22:50
  • they are driven from a text file, so they can and do change monthly, which is why I am trying to have it just sort whatever is populated in... – CVP Dec 10 '13 at 22:54
  • So the first menu is really just a sorting option for the secondary menu? – wrxsti Dec 10 '13 at 22:55
  • it's a brand selector, then the 2nd is a series selector, the third is a model.... (cause there's hundreds of models) – CVP Dec 10 '13 at 23:04
  • will try this in the morning you rock, it looks like it will be great! :) – CVP Dec 10 '13 at 23:08
  • Good deal. Hope it helps! – wrxsti Dec 10 '13 at 23:09