隐藏下拉选项基于选定的单选按钮,也对网页的onload

问题描述 投票:1回答:1

我有一个单选按钮和下拉列表的形式。

如果用户选择“女孩”,我只想显示caroms和国际象棋,如在girlsGames变量指定。

如果用户选择的男生,我想说明的boysGames变量的下拉选项。

这里是我的代码:

<form action="">
    <label for="boys"><input type="radio" id="boys" name="gender" value="boys">Boys</label>
    <label for="girls"><input type="radio" id="girls" name="gender" value="girls">Girls</label>
    <select name="games" id="">
    <option value="">select games</option>
    <option value="caroms">Caroms</option>
    <option value="chess">Chess</option>
    <option value="football">Football</option>
    <option value="rugby">Rugby</option>
    </select>
  </form>
    <script>
    var girlsGames = ['caroms', 'chess'];
            $('input:radio').change(function(event) {

          });
    </script>
javascript jquery dynamic-arrays
1个回答
2
投票

这是许多方法的基础上加入类特定选项和隐藏/显示所有选项之一:

var girlsGames = ['caroms', 'chess'];
            $('input:radio').change(function(event) {
             
              if(event.target.value == 'girls') {
                 $('option').hide();
                 $('.girls').show();
              } else if (event.target.value == 'boys'){
                 $('option').show();
              }
              
          });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
    <label for="boys"><input type="radio" id="boys" name="gender" value="boys">Boys</label>
    <label for="girls"><input type="radio" id="girls" name="gender" value="girls">Girls</label>
    <select name="games" id="">
    <option value="" class="girls">select games</option>
    <option value="caroms" class="girls">Caroms</option>
    <option value="chess" class="girls">Chess</option>
    <option value="football">Football</option>
    <option value="rugby">Rugby</option>
    </select>
  </form>
© www.soinside.com 2019 - 2024. All rights reserved.