Search code examples
pythonjquerydjangoadmin

Add jQuery to Django Admin Page for Dropdown Selection to Enable/ disable it


I have a model in Django which contains dropdowns and they are dependent. If I select "Yes" in a, the dropdowns associated with it i.e. b and c should be enabled and if "No", they should be disabled.

Note that I want this to work on admin page.

models.py

class foo(models.Model):
   a = models.CharField(max_length=3,choices=(('No','No'),('Yes','Yes'))
   b = models.ForeignKey(SomeModel_1,,on_delete=models.CASCADE,null=True,blank=True)
   c = models.ForeignKey(SomeModel_2,,on_delete=models.CASCADE,null=True,blank=True)

jQuery

$(function() {
$("#id_a").change(function() {
    if ($(this).val() == "Yes") {
        $("#id_b").prop("disabled", false);
        $("#id_c").prop("disabled", false);
    } else {
        $("#id_b").prop("disabled", true);
        $("#id_c").prop("disabled", true);
    }

});
})(django.jQuery);

And I have also added Media class

admin.py

class fooAdmin(admin.ModelAdmin):

class Media:
    js = ('https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',
    'js/myScript.js',)


admin.site.register(foo,fooAdmin)

Now, the dropdown b and c are available regardless of choice selected in a. How can I make this work? If I need forms.py then please explain how can I do that.

Thank you.


Solution

  • I suppose you have checked if your script is loading correctly.

    The problem is that your JS function is called before the DOM is completely loaded, so that jQuery queries do not find the elements when called. Wrap your jQuery in $(document).ready():

    $(document).ready(function(){
        $(function() {
        ...
    

    Then it is called after your page is completly loaded and the required elements are found.