javascript 在 Select2 中显示多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16556261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display multiple columns in Select2
提问by opensas
I'm using select2and I'd like to show a multicolum table as a drop down, so I need the width of the drop down container to have a different (larger) width than the input itself
我正在使用select2并且我想将多列表显示为下拉列表,因此我需要下拉容器的宽度与输入本身的宽度不同(更大)
Is it possible to do that?
有可能这样做吗?
moreover I'd like to show a table with several columns. From the movies example, I saw that in the formatResult function you create a new table for each row.
此外,我想显示一个包含几列的表格。从电影示例中,我看到在 formatResult 函数中,您为每一行创建了一个新表。
Would it be possible to include every row in the same table, so that every cells has the same width? I would need to set some template to contain the rows or something like that.
是否可以在同一个表格中包含每一行,以便每个单元格都具有相同的宽度?我需要设置一些模板来包含行或类似的东西。
What I want to achieve is a small input to show the code of an entity, and a large dropdown to show several more columns
我想要实现的是显示实体代码的小输入,以及显示更多列的大下拉列表
--
——
here's a related issue on github: https://github.com/ivaynberg/select2/issues/1314
这是 github 上的一个相关问题:https: //github.com/ivaynberg/select2/issues/1314
回答by A. Murray
I haven't had any success yet with having a fixed header row above the columns to act as a typical table header row, but in terms of actually getting the columns out there, I referred to this feature request on Githubwhere user trebuchetty alludes to using bootstrap's grid styles like col-md-6 (bootstrap versions >= 3).
我还没有取得任何成功,在列上方有一个固定的标题行作为典型的表格标题行,但就实际获取列而言,我在 Github上提到了这个功能请求,用户 trebuchetty 提到使用引导程序的网格样式,如 col-md-6(引导程序版本 >= 3)。
I tried the following in the select2 options and it seems to give good results:
我在 select2 选项中尝试了以下操作,它似乎给出了很好的结果:
formatResult: function(result) {
return '<div class="row">' +
'<div class="col-md-6">' + result.name + '</div>' +
'<div class="col-md-6">' + result.manager + '</div>' +
'</div>';
},
resultin the above is a reference to an element in the array of items displayed in the dropdown
上面的结果是对下拉列表中显示的项目数组中元素的引用
回答by Meloman
formatresultdidn't work for me ! But templateResult works finelike this with data form PHP in HTML generated (not ajax content).
formatresult对我不起作用!但是templateResult像这样使用 HTML 中的数据表单 PHP 生成的(不是 ajax 内容)工作得很好。
Here is woorking code for me, I seperate my columns by a pipe char (we could have more than 2 columns) :
这是我的工作代码,我用管道字符分隔我的列(我们可以有超过 2 列):
html (from PHP) :
html(来自PHP):
<option value="...">
column 1 text | column 2 text
</option>
javascript (jQuery) :
javascript (jQuery) :
$('#selectSubstance').select2({
templateResult: function(data) {
var r = data.text.split('|');
var $result = $(
'<div class="row">' +
'<div class="col-md-3">' + r[0] + '</div>' +
'<div class="col-md-9">' + r[1] + '</div>' +
'</div>'
);
return $result;
}
});
回答by BrinkDaDrink
I wanted to give my solution which will hopefully help others.
我想给出我的解决方案,希望能帮助其他人。
Using Select2 v4 tableish styling and multicolumn search. This uses local JSON data.
使用 Select2 v4 tableish 样式和多列搜索。这使用本地 JSON 数据。
Quick overview of how this works:
其工作原理的快速概览:
There are 2 functions. The matcher
function and the formatSelect
.
有2个功能。该matcher
功能和formatSelect
。
The matcher
function is used for the query. It will check each word of the query to see if there is a match in any of the rows. Currently set to return any row that matches atleaast 1 word.
该matcher
函数用于查询。它将检查查询的每个单词以查看任何行中是否存在匹配项。当前设置为返回匹配至少 1 个单词的任何行。
The formatSelect
function is then run once the matcher
has returned all matching rows (all rows if no query). formatSelect
adds header columns on the first row of data if its the first row being rendered.
formatSelect
一旦matcher
返回了所有匹配的行(如果没有查询,则为所有行),然后运行该函数。 formatSelect
如果第一行正在呈现,则在第一行数据上添加标题列。
The table in this case uses bootstrap column widths for structure.
本例中的表格使用引导列宽度进行结构化。
The code:
代码:
var firstEmptySelect = true;
function formatSelect(result) {
if (!result.id) {
if (firstEmptySelect) {
console.log('showing row');
firstEmptySelect = false;
return '<div class="row">' +
'<div class="col-xs-3"><b>Client</b></div>' +
'<div class="col-xs-3"><b>Account</b></div>' +
'<div class="col-xs-3"><b>Deal</b></div>' +
'</div>';
} else {
console.log('skipping row');
return false;
}
console.log('result');
console.log(result);
}
return '<div class="row">' +
'<div class="col-xs-3">' + result.client_name + '</div>' +
'<div class="col-xs-3">' + result.account_name + '</div>' +
'<div class="col-xs-3">' + result.deal_name + '</div>' +
'</div>';
}
function matcher(query, option) {
firstEmptySelect = true;
if (!query.term) {
return option;
}
var has = true;
var words = query.term.toUpperCase().split(" ");
for (var i =0; i < words.length; i++){
var word = words[i];
has = has && (option.text.toUpperCase().indexOf(word) >= 0);
}
if (has) return option;
return false;
}
$('#selectAccountDeal').select2({
data: {!! $deals !!},
width: '100%',
templateResult: formatSelect,
templateSelection: formatSelect,
escapeMarkup: function(m) { return m; },
matcher: matcher
})
My example JSON data
我的示例 JSON 数据
[{
"text": "JL - o yea - Testing this deal",
"id": 4,
"client_name": "JL",
"account_name": "o yea",
"deal_name": "Testing this deal"
}, {
"text": "JL - test - fj;askld fj",
"id": 3,
"client_name": "JL",
"account_name": "test",
"deal_name": "fj;askld fj"
}]
HTML for select element
选择元素的 HTML
<select id="selectAccountDeal" name="account_deal_id" placeholder="Select your Deal" required>
<option></option>
</select>
Example of the select2 dropdown
select2 下拉列表的示例
回答by chemark
If you use Select2 v3.5, here is a workaround:
如果您使用 Select2 v3.5,这里有一个解决方法:
function formatResultMulti(data) {
var city = $(data.element).data('city');
var classAttr = $(data.element).attr('class');
var hasClass = typeof classAttr != 'undefined';
classAttr = hasClass ? ' ' + classAttr : '';
var $result = $(
'<div class="row">' +
'<div class="col-md-6 col-xs-6' + classAttr + '">' + data.text + '</div>' +
'<div class="col-md-6 col-xs-6' + classAttr + '">' + city + '</div>' +
'</div>'
);
return $result;
}
$(function() {
$('#multi').select2({
width: '100%',
formatResult: formatResultMulti
});
})
body{
background-color: #455A64;
}
#multiWrapper {
width: 300px;
margin: 25px 0 0 25px;
}
.def-cursor {
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.0/select2.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.0/select2.min.js"></script>
<div id='multiWrapper'>
<select id="multi">
<optgroup class='def-cursor' label='Country' data-city='City'>
<option data-city="Athens" id="1" selected>Greece</option>
<option data-city="Rome" "id="2 ">Italy</option>
<option data-city="Paris " "id="3">France</option>
</optgroup>
</select>
</div>
回答by Xiaohui
Here is my solutions. My select2 version is 4.0.3.
这是我的解决方案。我的 select2 版本是 4.0.3。
The final presentation look like: select2-dropdown-table.
最终的演示文稿看起来像: select2-dropdown-table。
First add the header when select2 dropdown open:
首先在 select2 下拉菜单打开时添加标题:
var headerIsAppend = false;
$('#stock').on('select2:open', function (e) {
if (!headerIsAppend) {
html = '<table class="table table-bordered" style="margin-top: 5px;margin-bottom: 0px;">\
<tbody>\
<tr>\
<td width="20%"><b>药品名称</b></td>\
<td width="10%"><b>成本价</b></td>\
<td width="20%"><b>供应商</b></td>\
<td width="10%"><b>批号</b></td>\
<td width="20%"><b>有效期</b></td>\
<td width="20%"><b>库存数量</b></td>\
</tr >\
</tbody>\
</table>';
$('.select2-search').append(html);
$('.select2-results').addClass('stock');
headerIsAppend = true;
}
});
Then
然后
templateResult: function (repo) {
if (repo.medicine) {
var html = '<table class="table table-bordered" style="margin-bottom: 0px;">\
<tbody>\
<tr>\
<td width="20%">' + repo.medicine.name + '</td>\
<td width="10%">' + repo.costPrice + '</td>\
<td width="20%">' + repo.vendor + '</td>\
<td width="10%">' + repo.batchNum + '</td>\
<td width="20%">' + repo.expiredDate + '</td>\
<td width="20%">' + repo.quantity + '</td>\
</tr >\
</tbody>\
</table>';
return $(html);
}
},
The rest work need to do is adjust the css:
剩下的工作就是调整css:
.stock .select2-results__option {
padding: 0px 4px;
}
That's all.
就这样。
回答by Hoong
I using SELECT2 V4. Thank to BrinkDaDrink idea. I did some modification and simplified the code. below is my sample:
我使用 SELECT2 V4。感谢 BrinkDaDrink 的想法。我做了一些修改并简化了代码。以下是我的示例:
var firstEmptySelect = true; // Indicate header was create
function s2FormatResult(item) {
if (!item.id) {
// trigger when remote query
firstEmptySelect = true; // reset
return item.text;
}
var $container; // This is custom templete container.
// Create header
if (firstEmptySelect) {
firstEmptySelect = false;
$container = $(
'<div class="row">' +
'<div class="col-xs-3"><b>Product ID</b></div>' +
'<div class="col-xs-3"><b>Product Name</b></div>' +
'</div>' +
'<div class="row">' +
'<div class="col-xs-3">' + item.id + '</div>' +
'<div class="col-xs-3">' + item.text + '</div>' +
'</div>'
);
}
else {
$container = $('<div class="row">' +
'<div class="col-xs-3">' + item.id + '</div>' +
'<div class="col-xs-3">' + item.text + '</div>' +
'</div>');
}
return $container
}
回答by Math-Asteos
My example (based on Meloman's answer) can maybe help someone else :
我的例子(基于 Meloman 的回答)也许可以帮助别人:
// HTML
<select
class="form-control select2"
data-col0htmldebut="<div class='col-md-6'>"
data-col0htmlfin="</div>"
data-col1htmldebut="<div class='col-md-2'>"
data-col1htmlfin="</div>"
data-col2htmldebut="<div class='col-md-4'>"
data-col2htmlfin="</div>">
<option value="">Select...</option>
<option value="-1">Text with no column</option>
<option value="1">Column1__|__Col2__|__Col3</option>
<option value="2">Column1__|__Col2__|__Col3</option>
</select>
$("select.select2").select2({
templateResult: function (data) {
if (data.element == null) return data.text;
/************** Just one column handler **************/
// __|__ text seperator between each col find ?
var arrTexteOption = data.text.split('__|__');
if (arrTexteOption.length <= 1) return data.text;
/************** Multi column handler **************/
// Get select object
var objSelect = $("#" + data.element.parentNode.id);
// 4 column handled here
var arrStyleColDébut = [];
var arrStyleColFin = [];
for (var i = 0; i < 4; i++)
{
if (objSelect.attr('data-col' + i + 'htmldebut')) arrStyleColDébut.push(objSelect.data("col" + i + "htmldebut"));
if (objSelect.attr('data-col' + i + 'htmlfin')) arrStyleColFin.push(objSelect.data("col" + i + "htmlfin"));
}
if (arrTexteOption.length != arrStyleColDébut.length) return data.text;
var $htmlResult = '<div class="row">';
for (var i = 0; i < arrTexteOption.length; i++)
{
$htmlResult += arrStyleColDébut[i] + arrTexteOption[i] + arrStyleColFin[i];
}
$htmlResult += "</div>";
return $($htmlResult);
},
templateSelection: function (data) {
// Selection must display only the first col.
return data.text.split('__|__')[0];
}
});
回答by fidel castro
refer this it may helpful, here a component to make columns in select2 like structure https://github.com/suriyagp/Grid-Select
参考这可能会有所帮助,这里有一个组件可以在 select2 中创建列,如结构 https://github.com/suriyagp/Grid-Select