简体   繁体   中英

Sorting drop down menus when changed

I have a page that builds drop down menus dynamically from the database as follows:

<select name="set_order[]" class="form-control" data-catid="3">
    <option value="1" selected="">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select name="set_order[]" class="form-control" data-catid="2">
    <option value="1">1</option>
    <option value="2" selected="">2</option>
    <option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3" selected="">3</option>
</select>

What I want to do is that when one of them is changed, I want to resort the drop downs according to the change that was made with Javascript and update the selected dropdown in each dropdown so as that each drop down has a unique choice made.

I've been trying to sort them but I haven't been successful.

Thank you in advanced!

Edit, as requested, here is my trial JS to sort them:

$(document).on('change', 'select[name="set_order[]"]', function(){
    var newOrder = $(this).val();
    var change_id = $(this).attr('data-catid');

    console.log(newOrder, ' ', change_id);

    var order = new Array();
    var cat_id = new Array();

    var checker = false;
    $('select[name="set_order[]"]').each(function(i){
        order[i] = parseInt($(this).val());
        cat_id[i] = parseInt($(this).attr('data-catid'));

        console.log(order[i], ' ', cat_id[i], ' ', i);

        if(checker == false){
            if(cat_id[i] == change_id){
                checker = true;
            }else{
                order[i] = order[i] + 1 ;
            }
        }else{
            order[i] = order[i] - 1;
        }

        //console.log(order[i], ' ', cat_id[i], ' ', i);
    });


});

You can do that with jQuery

//Sort alphabetically the contact list in the biography page
function sortList() {
//Replace #list by the id of the div who enclose your select
    $("#list").html(
        $(".form-control").children("option").sort(function (a, b) {

            return $(a).text().toUpperCase().localeCompare(

            $(b).text().toUpperCase());
        })
    );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM