How to display selected item from Bootstrap dropdo

2019-08-20 08:59发布

问题:

I know this question has been asked and answered a lot, but I still can't figure it out within my code.

Updated code

  {% trans_default_domain 'Documents' %} 

      <div class="row">
          <div class="col-md-6">
              <div class="form-group">
        <label for="documentDropdown">{{ form_label(form.type) }}</label>
  <select class="form-control" id="documentDropdown">
  <option value="" selected disabled>Select Document Type</option>
  <option value="1" href="#">{{ 'document_types.contract'|trans }}</option>
  <option value="2" href="#">{{ 'document_types.general'|trans }}</option>
  <option value="3" href="#">{{ 'document_types.goodwill_policy'|trans }}</option>
  <option value="4" href="#">{{ 'document_types.pricesheet'|trans }}</option>
  <option value="5" href="#">{{ 'document_types.yq_update'|trans }}</option>
  <option value="6" href="#">{{ 'document_types.contract_addendum'|trans }}</option>
</select>
</div>

          <div class="col-md-6" id="vka">
              {{ form_row(form.vka_number) }}
          </div>
      </div>

      <div class="row">
          <div class="col-md-6">
              {{ form_row(form.active) }}
          </div>
          <div class="col-md-6 hidden">
              {{ form_row(form.signature) }}
          </div>
      </div>


      {% block javascripts %}
      <script>
        $(function(){
          $('.dropdown-menu').on( 'click', 'a', function() {
            var text = $(this).html();
            var htmlText = text + ' <span class="caret"></span>';
            $(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);
          });

        });

        $(document).ready(function(){
          $('#documentDropdown').on('change', function(){
            if (this.value == '1')
            {
              $('#vka').show();
            }
            else {
              $('#vka').hide();
            }
          });
        });
      </script>
        {% endblock %}

This is the code for my dropdown, and when selecting a value from the dropdown list, it is not displayed in the dropdown button. I feel like my whole JavaScript part is not working, since the "hide & show" part doesn't work either. Any ideas?

回答1:

you probably need something like this

$('#documentDropdown').find(":selected").text();

for value

$('#documentDropdown').find(":selected").val();