I want to do a three-level hierarchical category, subcategory and sub-subcategory with select tag using JQuery. Actually, it works. But, there is a bug. It only works for the first time. When I choose a category, it shows subcategory. Then, when I choose subcategory, it shows sub-subcategory. That’s good. But, when I change category without reloading the page, it shows duplicate subcategories. I don’t know why, but I think it might be due to not understanding JQuery live function. Here is the code. There are some twig tags (from Symfony 2) used.
Please, help.
$(document).ready(function() {
var options = '<select><option value="0">--Select--</option>';
{% for catalog in catalogs %}
options += '<option value="{{ catalog.id }}">{{ catalog.name }}</option>';
{% endfor %}
options += '</select>';
$('#form_item_add').html(options);
$('#form_item_add select').change(function() {
$(this).nextAll($(this)).remove();
$.getJSON('{{ path('subcatalog_list') }}', {catalog: $(this).val()}, function(json) {
if (json.length !== 0)
{
options = '<select><option value="0">--Select--</option>';
for (var i = 0; i < json.length; i++)
{
options += '<option value="' + json[i].c_id + '">' + json[i].c_name + '</option>';
}
options += '</select>';
$('#form_item_add').append(options);
$('#form_item_add select').live('change', function() {
$(this).nextAll($(this)).remove();
$.getJSON('{{ path('subcatalog_list') }}', {catalog: $(this).val()}, function(json) {
if (json.length !== 0)
{
options = '<select><option value="0">--Select--</option>';
for (var i = 0; i < json.length; i++)
{
options += '<option value="' + json[i].c_id + '">' + json[i].c_name + '</option>';
}
options += '</select>';
$('#form_item_add').append(options);
}
});
});
}
});
});
});
My Controller (Symfony 2)
/**
* @Route("/subcatalogs", name = "subcatalog_list")
*/
public function getSubcatalogAction(Request $request)
{
if ($request->isXmlHttpRequest())
{
$repository = $this->getDoctrine()->getRepository('TradeTradeBundle:Catalog');
$query = $repository->createQueryBuilder('c')
->where('c.parent = :parent')
->setParameter('parent', $request->get('catalog'))
->getQuery();
$subcatalogs = $query->getScalarResult();
return new Response(json_encode($subcatalogs));
}
return $this->render('TwigBundle:Exception:error.html.twig', array('status_code' => 404, 'status_text' => 'Page not found'));
}
I solved it on my own: