[Django]-How to hide Django form fields using JavaScript, Jquery etc

3👍

first go to django shell and then do the following:

python manage.py shell

from yourapp.yourform import ComponentForm
f = ComponentForm()
print(f.as_p())

this will give you all the id and class names you can use in your javascript or CSS to manipulate.

lets say you want to hide length then you will do:

$(document).ready(function(){
    $('#id_length').hide();
})
👤sgauri

2👍

Ok I solved the problem. When the user selects the PIPE option form the component_type dropdownlist the k_v field is hidden and the DI and length fields are shown. When the user selects the k_v option from the component_type dropdownlist the k_v field is shown and the length and DI fields are hidden.

My Django template is now as follows:

{% extends 'base.html' %}

<script>
{% block jquery %}

    // Call hideShow when page is loaded
    $(document).ready(function(){
        hideShow()
    })

    // call hideShow when the user clicks on the component_type dropdownlist
    $('#id_component_type').click(function(){
        hideShow()
    });

// The jquery function below hides/shows the k_v, DI and length fields depending on the selected component_type 
function hideShow(){
    if(document.getElementById('id_component_type').options[document.getElementById('id_component_type').selectedIndex].value == "1")
    {
        $('#id_length').parents('p:first').hide();
        $('#id_DI').parents('p:first').hide();
        $('#id_k_v').parents('p:first').show();
    }else
    {
        $('#id_length').parents('p:first').show();
        $('#id_DI').parents('p:first').show();
        $('#id_k_v').parents('p:first').hide();
    }
}
{% endblock %}
</script>


{% block content %}
<form method='POST'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Save</button>
</form>
{% endblock %}
👤arne

Leave a comment