使用Jquery只显示选中的选项

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

如何只显示选中的选项,隐藏所有未选中的选项?

我的代码只显示复选框,不显示标签,请问如何只显示选中的选项,而隐藏所有未选中的选项?

$("#checked_show").click(function() {

  $("input").hide();
  $("label").hide();
  $("input:checked").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>

<br /><br />

<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

<br /><br />

<button id="checked_show">Show only Checked</button>

如何只显示选中的选项,而隐藏所有未选中的选项?

我的代码只显示复选框,不显示标签,如何只显示选中的选项,而隐藏所有未选中的选项?

javascript jquery checkbox radio-button checked
1个回答
0
投票

你可以使用 input:checked 结合 :not() 来选择没有被选中的输入。

$("#checked_show").click(function() {

  $("input:not(:checked)").each((i, el) => {
    $(el).next().hide();
    $(el).hide();
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>

<br /><br />

<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

<br /><br />

<button id="checked_show">Show only Checked</button>

0
投票

您应该使用 :checked 来选择被选中的输入,并用 :not()如果要隐藏标签,你还必须在所有元素中循环,并使用以下方法选择下一个元素 .next(),这里有一个工作片段。

$("#checked_show").click(function () {
  if ($("input[type='checkbox']:checked").length) {
    $("input[type='checkbox']:not(:checked)").each(function (idx, el) {
      $(el).next().hide();
      $(el).hide();
    });
  } else {
    console.log('Please select an input!');
  }
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>

<br /><br />

<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

<br /><br />

<button id="checked_show">Show only Checked</button>
© www.soinside.com 2019 - 2024. All rights reserved.