Input a name into a text field, but submit an ID?
I have a form with a text_field in my app where I input the name of a book. The book already exists i开发者_如何转开发n my database. How can I submit the ID of the book in the form instead of the name?
I should mention that I don't want to use a collection select here, because I want this to eventually be an auto-complete field.
You should handle this logic with your autoselect.
$('.book_search').live('keyup.autocomplete', function(){
$(this).autocomplete({
source : '/ajax_functions/book_search',
select : function(event, ui){
book_id = ui.item.id;
label = ui.item.value;
$(this).before(label); // replace with text
$(this).before('<input name="books'+[book_id]" type="hidden" value="'+user_id+'">');
$(this).remove();
return false;
}
});
});
You're autocomplete json:
books = []
Book.search(params[:term]).each do |b|
books << { :label => b.name, :id => b.id }
end
render :json => books
This will do what you want. You'll still need to implement server logic to add new books that don't yet exist.
精彩评论