[英]How can I select from a full table with Selectize.js?
我正在尝试使用selectize-rails
gem。 如何使用selectize从整个表格中进行选择?
以下代码允许我多选“ Option1”和“ Option2”。
views / users / show.html.erb :
$('#select-to').selectize({
persist: false,
maxItems: null,
valueField: 'email',
labelField: 'name',
searchField: ['name', 'email'],
options: [
{email: 'option1@example.com', name: 'Option1'},
{email: 'option2@example.com', name: 'Option2'},
],
render: {
item: function(item, escape) {
return '<div>' +
(item.name ? '<span class="name">' + escape(item.name) + '</span>' : '') +
(item.email ? '<span class="email">' + escape(item.email) + '</span>' : '') +
'</div>';
},
option: function(item, escape) {
var label = item.name || item.email;
var caption = item.name ? item.email : null;
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
(caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
'</div>';
}
},
createFilter: function(input) {
var match, regex;
// email@address.com
regex = new RegExp('^' + REGEX_EMAIL + '$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[0]);
// name <email@address.com>
regex = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[2]);
return false;
},
create: function(input) {
if ((new RegExp('^' + REGEX_EMAIL + '$', 'i')).test(input)) {
return {email: input};
}
var match = input.match(new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i'));
if (match) {
return {
email : match[2],
name : $.trim(match[1])
};
}
alert('Invalid email address.');
return false;
}
});
如何从完整表格中选择? 例如,我有一个名为“ User”的表。 如何从User.all
选择,而不仅仅是预设选项?
schema.rb :
create_table "things", force: true do |t|
t.string "name"
t.string "email"
#...
end
根据docs ,您需要创建一个load
方法,该方法将使用选项数组调用callback
。 将preload设置为true会强制在创建选择时填充它。
在您的.selectize()中:
load: function(query, callback) {
$.ajax({
url: 'http://railshost/users.json',
type: 'GET',
dataType: 'json',
data: {
// query: query // if your data source allows
},
error: function() {
callback();
},
success: function(response) {
callback(response.table);
}
});
}
...
class UsersController < ApplicationController
def index
@users = User.all.where(type: "A")
respond_to do |format|
format.json { render json: @users}
end
end
end
由于它只有大约100个对象,因此我认为您无需在selectize代码中四处寻找; 您可以简单地使用Rails动态设置选项,然后选择使其看起来更漂亮。
这是我在应用程序中使用的方法,已针对您的情况进行了调整:
<select id='select-to'>
<option value="">Please select an option</option>
<% User.where(type: "A").each do |user| %>
<option value="<%= user.id %>"><%= user.name %></option>
<% end %>
</select>
然后只需选择#select-to。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.