I have successfully done ajax calls before for situations like this in a form:
- User selects a 'category' from a list in a select box. Ajax is fired off when selection is made, which updates a second select box with all items related to the selected category.
I know how to successfully do that thanks to the answer found here.
What I am now doing is dynamically adding new nested form fields with the nested_form_fields gem. Here is a snapshot:
So every time the user selects "Add Service", the nested_form_fields
gem generates a new nested form with two select boxes (a service category
select box and a service provided
select box as pictured above).
It works fine. The issue I am having is firing off an ajax request for this dynamic content when the user chooses a service category
.
When a user selects a service category
, I want to send an ajax call, which updates that second select box with all the services related to that service category
.
The issue is that the ajax request is not firing off at all. The server is not getting any requests when the user selects a service category
. I think the issue is that since these nested fields are generated dynamically, the javascript does not have the opportunity to bind the ajax request to the new nested fields' service category
select box.
Here is my javascript:
$(document).ready(function(){
$("#service_category_selection").on('change', function(){
$.ajax({
url: "narrow_service_by_service_category_selection",
type: "GET",
data: {service_category_id: $(this).val()},
success: function(data){
/* ... */
}
})
});
});
I think if I was somehow able to make this javascript run every time the html in the page changed (ex: when new nested form fields are added), then the javascript will able to bind that ajax call to the new service category
select box.