Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How hide/show a field upon selection of a radio button in django admin?

models.py

from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),)
class Leave(models.Model):
    ----
    ----
    ----
    ----
    status = models.IntegerField(choices=STATUS_CHOICES, default = 0)
    reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True)

    def __str__(self):
        return self.name

admin.py

from django.contrib import admin
from .models import Leave

@admin.register(Leave)
class LeaveAdmin(admin.ModelAdmin):
    ------
    ------
    -----

    class Media:
        js = ('/static/admin/js/admin.js')

- admin.js

    (function($) {
    $(function() {
        var reject = document.getElementById('id_status_0')
        var accept = document.getElementById("id_status_1")
        var reason_reject = document.getElementById("id_reason_reject")
        if (accept.checked == true){
            reason_reject.style.display = "none"
        }
        else{
            reason_reject.style.display = "block"
        }
    });
})(django.jQuery);

Now I have imported the file in the admin.py, How do I trigger the jQuery function such that it works.

update-

the function works but, I need to reload the page to make the field appear and disappear. I want some thing equivalent to 'on-click' event in HTML. I have no idea about Javascript.

like image 569
bhanuprakash Avatar asked Aug 24 '18 04:08

bhanuprakash


People also ask

How do you show and hide input fields based on radio button selection?

To show or hide an element when a radio button is selected: Add a click event handler to all input elements of type radio . Each time a radio button is selected, check if it is the button that should show the element. If it is, set the display property of the hidden element to block .

How do you show and hide input fields based on radio button selection in react?

Answer: Use the jQuery show() and hide() methods You can simply use the jQuery show() and hide() methods to show and hide the div elements based on the selection of radio buttons. The div boxes in the following example are hidden by default using the CSS display property which value is set to none .


1 Answers

$(function() {
    $('input[name="status"]').on('click', function() {
        if ($(this).val() == '0') {
            $('#id_reason_reject').show();
        }
        else {
            $('#id_reason_reject').hide();
        }
    });
})
like image 130
bhanuprakash Avatar answered Oct 05 '22 12:10

bhanuprakash