Lukas Lukas - 6 months ago 10
HTML Question

Using jQuery to select only one element of a type at a time

I want to be able to select only one card at a time, so if one is selected and another card is clicked on the first card will be unselected and the new one will become the selected card.

Thanks in advance!

https://jsfiddle.net/we5hm4an/



$('.option-card').click(function() {
if ($(this).hasClass('choice')) {
$(this).removeClass('choice');
} else {
$(this).addClass('choice');
}
});

.option-card {
width: 21.9%;
height: auto;
padding: 15px 15px 0;
margin: 0 10px 10px;
border: 2px #cfcfcf solid;
border-radius: 15px;
display: inline-block;
}
.option-card:first-of-type {
margin-left: 0;
}
.option-card:last-of-type {
margin-right: 0;
}
.option-card:hover,
.option-card.choice {
border: 2px #0079c1 solid;
text-decoration: none;
}
a.option-card p:hover {
text-decoration: none;
}
.card-thumb {
width: 100%;
border-radius: 50%;
margin-bottom: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>

<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>

<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>




Answer

This one is pretty simple.

$('.option-card').click(function() {
  $(".choice").removeClass("choice");
  $(this).addClass("choice");
});
.option-card {
    width: 21.9%;
    height: auto;
    padding: 15px 15px 0;
    margin: 0 10px 10px;
    border: 2px #cfcfcf solid;
    border-radius: 15px;
    display: inline-block;
}
.option-card:first-of-type {
    margin-left: 0;
}
.option-card:last-of-type {
    margin-right: 0;
}
.option-card:hover,
.option-card.choice {
    border: 2px #0079c1 solid;
    text-decoration: none;
}
a.option-card p:hover {
    text-decoration: none;
}
.card-thumb {
    width: 100%;
    border-radius: 50%;
    margin-bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>

<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>

<div class="option-card">
<img src="http://placekitten.com/100/100" class="card-thumb" alt="">
<p>Sodales feugiat etiam venenatis dui convallis</p>
</div>