I have two select elements in my form, Category and Subcategory. At first, only the category selection is displayed. When the user makes a selection in the select category, an AJAX request is sent to the server and the subcategory selection is displayed. It works great.
Now, when there is some kind of error in the submit form, because of something, some value that is required or something is missing, I am showing an error message, but I cannot save the same state in blocks of choice, I see only the choice of category, without the value selected, i.e. initial state. Can someone suggest me how I can save the state of these selection items?
Here is a snippet of code 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 is my jQuery script that sends an AJAX request when the choice is made by choosing a category:
$("#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; });
An AJAX request is executed in the update_sub_cat action in 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
AJAX request displays update_sub_cat.js.erb file in which I used some HMTL
sub-category <%= collection_select :post_sub_category, :id, @sub_categories, :id, :name, options = {:prompt => "Select a sub-category"} %>
I know that I should not directly use HTML here, but rather use $ ('sub-category-select) .append (...), but I got it like this and plan to change it later.
This is all the code that is involved in this part of my program.
Can someone help me please?