samedi 6 janvier 2018

Persistence issues with checkboxes

My Goal

Is to create a shopping webpage where users can filter through the product selection by checking checkboxes. Instead of having a "submit" button I wanted the page to submit as soon as the user checked the checkbox. Example: the "refine by" section on Amazon.

My Solution

The best way would have been to use AJAX however I opted for a simple javascript / jquery function instead:

$(":checkbox").change(function () {
    $('#product-filters').submit()
});

Clicking the checkbox would correctly refresh page and apply filters, however the checkbox would appear un-checked to the user. So in Django I implemented following workaround:

filters = request.GET.getlist('filters', None)
selected_filters = []
try:
    for f in filters:
        selected_filters.append(int(f))
except TypeError:
    selected_filters = None
return {
    # .....
    'selected_filters': selected_filters,
     }

And then in my template: <input Liquid error: Unknown operator in ... all my other attrs></input>

My Issue

While all of the above works correctly I now have the issue that if a user clicks on a checked checkbox in order to uncheck it, it will simply refresh the page and keep it checked, with that filter applied. How should I go about fixing this?




Aucun commentaire:

Enregistrer un commentaire