Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have styled some markup where the user can select a DIV and it shows highlighted.. this works fine, however, I want to only allow one DIV to be highlighted and selected at time.. currently the user can select all 3 DIVS and they will all show highlighted. I use jquery toggleClass to add/remove "active" class to DIV. "active" class is styled in css to show blue background.

how can I stop users from selecting all 3?

$('.pricecard.aircraft').click(function() {
  // this will fire when you click view
  $(this).toggleClass('active');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft active h-100">
    <div class="card-body">
      <span class="price1">£20,944</span></p>
    </div>
  </div>
</div>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft h-100">
    <div class="card-body">
      <span class="price2">£20,944</span></p>
    </div>
  </div>
</div>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft h-100">
    <div class="card-body">
      <span class="price3">£20,944</span></p>
    </div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

To achieve your goal call removeClass() on all the other .pricecard.aircraft elements which are not the one which was clicked on:

let $divs = $('.pricecard.aircraft').click(function() {
  $divs.not(this).removeClass('active');
  $(this).toggleClass('active');
});
.active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft active h-100">
    <div class="card-body">
      <span class="price1">£20,944</span>
    </div>
  </div>
</div>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft h-100">
    <div class="card-body">
      <span class="price2">£20,944</span>
    </div>
  </div>
</div>
<div class="col-sm-4 my-1">
  <div class="card pricecard aircraft h-100">
    <div class="card-body">
      <span class="price3">£20,944</span>
    </div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...