Django crispy form - use Radio button to hide/show

2019-08-03 07:26发布

问题:

please I have a question about creating a form using Django-crispy-form. I want to have a form which has 2 fields and the selection of the first field hides/shows the second one.

  • 1st field: Radio button <= this option hides/shows the second field.
  • 2nd field: Float field

What I've tried is:

  1. Assign id to Radio button, put the 2nd field into a div
  2. Run a JS function when clicking the radio button based on the assigned id.
  3. In the JS function, get the value of the radio button
  4. Based on the value, hide/show the div containing the 2nd field.

But at step 3, I always get "undefined value". I guess it's because I couldn't assign id to the choice/option, but only to the whole radio button which has no value. But it's just my guess. Please refer to my simple code, I would be very grateful if someone could help me out.

Thanks alot !!!

forms.py

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineRadios,PrependedAppendedText,Div

class my_form(forms.Form):
    # Radio button field
    cargo = forms.ChoiceField(label='Cargo on Deck',
                              choices=[('true','Yes'),
                                       ('false','No')],
                              initial='false')
    # the 2nd field
    L = forms.DecimalField(label='Length: L [m]')

    ### Render form
    def __init__(self, *args, **kwargs):
        super(my_form, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'my_form_id'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', 'Calculate'))

        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-4'
        self.helper.field_class = 'col-lg-8'

        # step 1: Assign id to radio, put 2nd field in a div
        self.helper.layout = Layout(
            InlineRadios('cargo',id="radio_id"),
            Div('L', css_id="div_id"),
        )

HTML

<!-- Html -->
{% extends 'home/home_base.html' %}
{% block content %}
    <div class="row">
      <div class="col-sm-6">
            <!-- {% csrf_token %}-->
            {% load crispy_forms_tags %}
            {% crispy my_form my_form.helper %}
      </div>
    </div>
    
    <!-- JS -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    
    <script type="text/javascript">
      // step 2: run function when clicking radio button
      $(document).ready(function() {
        $('#radio_id').on('change',function(){
            // step 3: get selected value
            var selected_value = $('input[id="radio_id"]:checked').val();
            alert(selected_value); // somehow this always gives "undefined value"
    
            // step 4: hide/show dive based on selected_value
             if( $(this).val()=="true"){
                $("#div_id").hide()
             }
             else{
                $("#div_id").show()
             }
         });
      });
    </script>
{% endblock %}

回答1:

For step 3 in the HTML file, try using:

$('input[name="cargo"]:checked').val();