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.
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 .
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 .
$(function() {
$('input[name="status"]').on('click', function() {
if ($(this).val() == '0') {
$('#id_reason_reject').show();
}
else {
$('#id_reason_reject').hide();
}
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With