I have two select elements in my form, Category and Sub-category. At first, only the category select is shown. When the user makes a selection in the category select, an AJAX request is sent to the server and the subcategory select is shown. It works fine.
Now, when there is some error in the form submit, due to anything, missing some value that is required, or anything, I show the error message, but I cannot retain the same state of the select boxes, I see only the category select, with no value selected, i.e the initial state. Can anyone suggest me how I can preserve the state of these select elements?
Here's a code snippet from my new form:
<div id="category-select">
category <%= collection_select :post_category, :id, @categories, :id, :name,
options = {:prompt => "Select a category"} %>
</div>
<div id="sub-category-select">
</div>
Here's my jQuery script that sends AJAX request when a selection is made on Category select:
$("#post_category_id").change(function() {
var category_id = $('select#post_category_id :selected').val();
if(category_id == "") category_id="0";
$.get('/posts/update_sub_cat/' + category_id, function(data){
$("#sub-category-select").html(data);
})
return false;
});
The AJAX request is made on the update_sub_cat action in the post_controller, which is shown below:
def update_sub_cat
if params[:id].present?
@sub_categories = Category.find_all_by_parent_id(params[:id])
else
@sub_categories = []
end
respond_to do |format|
format.js
end
end
The AJAX request renders update_sub_cat.js.erb file, in which I have used some HMTL
sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name,
options = {:prompt => "Select a sub-category"} %>
I know, I should not directly use HTML here, but rather use $('sub-category-select).append(...), but I got it working like this, and am planning to change it later.
This is all the code that is involved in this part of my program.
Can anyone help me, please?
See Question&Answers more detail:
os