[英]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.