Steven Eckhoff Steven Eckhoff - 1 year ago 52
HTML Question

Make form text field presence dependent on checkbox selection

I have a Django form and I would like it to initially hide a text field until the user selects a checkbox.

I am new to Django and web applications, so I have no idea what I am looking for or what it is called. I have searched to no avail. Any pointer would be helpful.

Answer Source

You are looking for Javascript instead of Django. Since Django does only backend serving and logic, it can't handle any changes happening in the front-end directly. If you don't need to interact with the backend at all during this process, you can simply make javascript (jQuery perhaps) listen for changes in the checkboxes states and if they change, make the form field visible. Form field can be prerendered with Django invisibly (i.e. using <input type="hidden">). Then you can remove the hidden state using Javascript.

If you do need to interact with backend, then you'll want to do basically the same thing with the exception that you render the page with Django, listen for checkbox changes and if the change occurs, you send an AJAX request to a Django view that handles that request and returns the data you need (i.e. from database or some complex calculations that shouldn't be in the front-end). To return the data, you can use Django's JsonResponse.