【问题标题】:Sorting drop down menus when changed更改时对下拉菜单进行排序
【发布时间】:2016-04-02 02:42:27
【问题描述】:

我有一个从数据库动态构建下拉菜单的页面,如下所示:

<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>

我想要做的是,当其中一个发生更改时,我想根据使用 Javascript 所做的更改来使用下拉菜单,并更新每个下拉菜单中的选定下拉菜单,以便每个下拉菜单都有一个唯一的做出的选择。

我一直在尝试对它们进行排序,但没有成功。

谢谢你!

按要求编辑,这是我对它们进行排序的试用 JS:

$(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);
    });


});

【问题讨论】:

  • 你是如何对它们进行排序的?你能给我们看看吗?
  • @Adjit 是的,让我发布我的 JS
  • 好的,你能解释一下你想如何更清楚地排序吗?您想使用所有其他 set_order[] 但是,您希望该排序如何工作?
  • @Adjit 因此,当下拉列表更改为不同的值时,我想对其余下拉列表选择的值进行排序,以便相应地更新每个下拉列表。
  • 对,但是你想怎么排序呢? AZ?数字顺序?基于某种价值?

标签: javascript jquery html drop-down-menu


【解决方案1】:

你可以用 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());
        })
    );
};

【讨论】:

  • 感谢您的评论。唯一的问题是我的下拉菜单是根据数据库中的记录制作的,我正在尝试更新多个下拉菜单,而不仅仅是一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
相关资源
最近更新 更多