applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to I get ID of fields rendered with django-select2?

wanjohikibui opened this issue · comments

Goal
I have a form in which I'm hiding or showing some fields based on the selection as the user fills the form. I'm hiding the fields using JQuery as below;

$("#id_house_code").hide();

I'm trying to get the id of a field in which I have used the Select2Widget widget. How do I do this, please?

Hi @wanjohikibui I guess you have figured it out by now. But just in case someone else looks for a solution:
Django usually creates ID's for it's inputs following a patterned defined by auto_id. The default pattern is id_%s. You can pass any other pattern when initializing your form or even pass False if you want id to be created for the inputs. In this case Django will also omit labels.
The auto_id pattern is rendered by each widget in their id_for_label method. So one could overwrite this method to change the behavior of a single widget.

I hope that answer helps you and other.

Best
-Joe

@wanjohikibui very good question. This happens because the Select2 input that you see, is not the select-tag. It is an additional div-container created by JavaScript. Maybe you might want to consider just disabling the input, you can find documentation on how to do that over here: https://select2.org/appearance#disabling-a-select2-control