Home > Enterprise >  JS hide all elements with same class except one
JS hide all elements with same class except one

Time:05-18

I got multiple checkboxes and some of them are with same class, name and value. How can I hide them except one with JS or Jquery? Here is my code which is echoing multiple checkboxes (there is a loop before them)

 <input style="width: auto;" type="checkbox" name="<?php the_field('tiker'); ?>" value="<?php the_field('tiker'); ?>">
 <label for="scales"><?php the_field('tiker'); ?></label>

Examples of outputed inputs:

    <div style="margin-top: 5px;"> 
<input style="width: auto;" type="checkbox" name="SBER" value="SBER"> 
<label for="scales">SBER</label>
<input style="width: auto;" type="checkbox" name="SBER" value="SBER"> 
<label for="scales">SBER</label> 
<input style="width: auto;" type="checkbox" name="vtbr" value="vtbr"> 
<label for="scales">vtbr</label> 
<input style="width: auto;" type="checkbox" name="APL" value="APL"> 
<label for="scales">APL</label>
</div>

CodePudding user response:

If the checkbox values are known in advanced then you could simply use css to select and hide the duplicates. We can't use pseudo classes like :first-child or :nth-child for this because we're selecting by attribute. Yet, we can use the general sibling combinator (~) to do the equivalent.

The css selector applies display:none to all but the first match as shown in the snippet. Note that you also need to hide the associated label too.

However, if the checkbox values aren't known in advance then you'd need to hide them with JavaScript. Even better, have PHP filter out the duplicates on the backend.

Also see: CSS select the first child from elements with particular attribute

input[value=SBER]~input[value=SBER],
input[value=SBER] label~input[value=SBER] label {
  display: none;
}
<div style="margin-top: 5px;">
  <input style="width: auto;" type="checkbox" name="SBER" value="SBER">
  <label for="scales">SBER</label>
  <input style="width: auto;" type="checkbox" name="SBER" value="SBER">
  <label for="scales">SBER</label>
  <input style="width: auto;" type="checkbox" name="vtbr" value="vtbr">
  <label for="scales">vtbr</label>
  <input style="width: auto;" type="checkbox" name="APL" value="APL">
  <label for="scales">APL</label>
  <input style="width: auto;" type="checkbox" name="SBER" value="SBER">
  <label for="scales">SBER</label>
</div>

  • Related