jQuery select change show/hide div event

前端 未结 9 1437
失恋的感觉
失恋的感觉 2020-11-27 17:34

I am trying to create a form which when the select element \'parcel\' is selected it will show a div but when it is not selected I would like to hide the div. Here is my mar

相关标签:
9条回答
  • 2020-11-27 18:23
    <script>  
    $(document).ready(function(){
        $('#colorselector').on('change', function() {
          if ( this.value == 'red')
          {
            $("#divid").show();
          }
          else
          {
            $("#divid").hide();
          }
        });
    });
    </script>
    

    Do like this for every value Also change the values... as per your parameters

    0 讨论(0)
  • 2020-11-27 18:28

    I used the following jQuery-based snippet to have a select-element show a div-element that has an id that matches the value of the option-element while hiding the divs that do not match. Not sure that it's the best way, but it is a way.

    $('#sectionChooser').change(function(){
        var myID = $(this).val();
        $('.panel').each(function(){
            myID === $(this).attr('id') ? $(this).show() : $(this).hide();
        });
    });
    .panel {display: none;}
    #one {display: block;}
    <select id="sectionChooser">
        <option value="one" selected>Thing One</option>
        <option value="two">Thing Two</option>
        <option value="three">Thing Three</option>
    </select>
    
    <div class="panel" id="one">
        <p>Thing One</p>
    </div>
    <div class="panel" id="two">
        <p>Thing Two</p>
    </div>
    <div class="panel" id="three">
        <p>Thing Three</p>
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-27 18:30

    Nothing new but caching your jQuery collections will have a small perf boost

    $(function() {
    
        var $typeSelector = $('#type');
        var $toggleArea = $('#row_dim');
    
        $typeSelector.change(function(){
            if ($typeSelector.val() === 'parcel') {
                $toggleArea.show(); 
            }
            else {
                $toggleArea.hide(); 
            }
        });
    });
    

    And in vanilla JS for super speed:

    (function() {
    
        var typeSelector = document.getElementById('type');
        var toggleArea = document.getElementById('row_dim');
    
        typeSelector.onchange = function() {
            toggleArea.style.display = typeSelector.value === 'parcel'
                ? 'block'
                : 'none';
        };
    
    });
    
    0 讨论(0)
提交回复
热议问题