防止多个select元素根据选项中索引的顺序自动排序分配给它的值 [英] Prevent multiple select element from automatically sorting the value assigned to it basis the order of the indexes in the options

查看:136
本文介绍了防止多个select元素根据选项中索引的顺序自动排序分配给它的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用select2插件将一个多选html元素转换为一个更可呈现的格式。另外我不认为我的问题非常依赖插件。



插件在内部做了什么 -

  this.select.val(VAL); 

其中 this.select 指向隐藏多个选择元素。



在提供高于val的函数 - 2,4,0 时,

当我执行一个 alert(this.select.val()) 0,2,4 时存储为已确认的值,即使用自动不需要的排序根据select元素中选项的顺序。 。 :/ b
$ b

DEMO -


I am using the select2 plugin to convert a multiple select html element to a more presentable format. Also I don't think my question is very much dependent on the plugin.

What the plugin does internally is -

this.select.val(val);

where this.select points to the hidden multiple select element.

On feeding the function above a val of say - 2,4,0 ,
the value stored as confirmed when I do an alert(this.select.val()) is 0,2,4 , i.e. with automatic unwanted sorting according to the order of the options in the select element.. :/

DEMO - http://jsfiddle.net/rohanxx/DYpU8/ (thanks to Mark)

Is there a way to preserve the sort order after feeding in the value to my select element?

Thanks.

解决方案

This is a very good question. I think this is more to do with the multiselect html element, rather than select2.

If you have a normal multiselect, there is no "order" sort of speak. You just have a list in the original order, with either each item selected or not.

I'm almost 100% sure there is a better way of doing this than the below, but for a workaround it should do just fine.

End result:

JavaScript code

// 'data' brings the unordered list, while 'val' does not
var data = $('#e1').select2('data');

// Push each item into an array
var finalResult = [];
for( item in $('#e1').select2('data') ) {
    finalResult.push(data[item].id);
};

// Display the result with a comma
alert( finalResult.join(',') );

JSFiddle:

http://jsfiddle.net/DYpU8/4/

这篇关于防止多个select元素根据选项中索引的顺序自动排序分配给它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆