Select2 vs Chosen

Select2 and Chosen are both great javascript widgets for enhancing the HTML select tag. They have a lot of similarity and a few differences. How to pick? These just a few issues I have run into. I am using Select2 V4 and Chosen 1.1.

Form Tabbing

A lot of users prefer keyboard to a mouse. Both widgets allow that. However, Chosen handles tab better. With Chosen, tab completes the entry and moves to the next form field. With Select2, I could not get tab to move to the next field. Select2 messes with the tabindex property. I am guessing that is part of the problem.

Tagging

This is the reason I used Select2 instead of Chosen. Tagging allows the user to input something that is not already in the select widget.

 

 

Advertisements

Passing Arrays From Django To Javascript

To pass an array from Django to Javascript, you must convert it to a string first and then pass it to the template as part of the context. If your array contains strings then you need to be careful to properly enclose each string in quotes, which is a pain if the string contains quotes. A great solution is to use json. Like this:

# In your python code
import json
options = [[x.id, unicode[x] for x in my_model.objects.all()]
options_for_js = json.dumps(options)

# In your Django template
var my_array = {{ options_for_js|safe }}