我有一个包含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
请帮我继续前进
答案 0 :(得分:0)
我使用http://www.appelsiini.net/projects/chained之类的内容。
如果你想自己做:
你的书需要输出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);
};
答案 1 :(得分:0)
您需要从所选Collection的服务器获取Json数据,然后填充Book Dropdown。所以这是一个代码片段
服务器端
def get_books
collection_id = params[:some_id]
@books = Book.where(collection_id: collection_id)
render :json=> @books.map {|book| {:id=>book.id,:title=>book.name}}
end
<强>:JavaScript的强>
// generate books based on chosen collection
$(function() {
$('select#reader_collection').change(function() {
var id = $(this).find(":selected").val();
$.get(("/get_books/?some_id="+id),function(data){
$.each(data, function( index, book ) {
$(YOUR_BOOK_DROPDOWN_SELECTOR).append($('<option>').text(book.title).attr('value', book.id))
});
});
});
});
将 YOUR_BOOK_DROPDOWN_SELECTOR 替换为您实际的Dropdown ID / Selector for Book。
P.S不测试自己。可能会有一些小故障