Reputation: 3698
I am trying to implement chained dependent dropdown combobox selection. I have a 'category' HTML combobox and once the value in there is changed, another combobox should appear to select a subcategory and so on until the innermost (most specific) category is selected. So, whenever the value in the combobox is changed I am firing an AJAX GET request which should reload only that bit of the page, however currently my code just duplicates entire page instead of just creating a new <select>
.
Here is my Django template with the jQuery code:
{% extends 'pages/base.html' %}
{% block content %}
<h1>Create a product</h1>
<form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}">
{{ form.as_p }}
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_category").change(function () {
var url = $("#productForm").attr("data-product-url");
var categoryId = $(this).val();
$.ajax({
url: url,
data: {
'category': categoryId
},
success: function (data) {
$("#productForm").append(data);
}
});
});
</script>
{% endblock %}
Here is my view:
def load_categories(request):
category_id = request.GET.get('category')
subcategories = Category.objects.get(id=category_id).get_children()
return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories})
Here is my urls.py
:
app_name = 'products'
urlpatterns = [
path('create/', product_create_view, name='product-create'),
path('ajax/load-categories/', load_categories, name='ajax_load_categories')
]
and here is the tiny bit of HTML I am trying to create:
products/category_dropdown_list_options.html
<select>
{% for subcategory in subcategories %}
<option value="{{ subcategory.pk }}">{{ subcategory.name }}</option>
{% endfor %}
</select>
Upvotes: 0
Views: 396
Reputation: 536
Change this var url = $("#productForm").attr("data-product-url");
to var url = $("#productForm").attr("data-products-url");
Upvotes: 1