我有一个包含 2 个下拉列表的表单:收藏和书籍。第一个下拉列表显示所有集合。除非选择了某些集合,否则第二个下拉列表必须为空。并且只有当用户选择一个集合时,第二个下拉列表才必须充满该集合中的书籍。
我的 haml 文件:
= simple_form_for 'reader', url: generate_reader_path do |f|
= f.input :collection, :collection => @collections.map{|c| [c[:name], c[:id]]}, input_html: { url: get_books_collections_path}
%br
= f.input :book, :collection => @books.map{|b| [b[:name], b[:id]]}
:javascript
// generate books based on chosen collection
$(function() {
$('select#reader_collection').change(function() {
var id = $(this).find(":selected").val();
var params = 'some_id=' + id;
});
});
当用户选择一个集合时,他应该进入 collections_controller 中的 get_books 方法:
def get_books
collection_id = params[:some_id]
@books = Book.where(collection_id: collection_id)
end
请帮助我继续前进
最佳答案
我会使用类似 http://www.appelsiini.net/projects/chained 的东西.
如果你想自己做:
你的get books需要输出json:
def get_books
collection_id = params[:some_id]
@books = Book.where(collection_id: collection_id)
render json: @books
end
JavaScript:
:javascript
// generate books based on chosen collection
$(function() {
$('select#reader_collection').change(function() {
var id = $(this).find(":selected").val();
var params = 'some_id=' + id;
$.ajax({
#You could use the url set on the first select, set it to an data attribute and retrieve it here with $(select).data 'url'
url: "/controller/action?id=" + id,
type: 'get',
data: $(this).serialize()
}).success(function (data) {
update_select(data);
});
});
});
function update_select(data) {
var json = jQuery.parseJSON(data);
var options = [];
json.each(function (key, index) {
options.push({text: index, value: key});
});
$("#select_box").replaceOptions(options);
};
关于javascript - simple_form_for 中的相关下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35339177/