My task involves creating a dynamic HTML form that allows users to enter card values, which are then counted and styled accordingly. Each set of cards is contained within a <section>
element.
However, I encountered an issue with my jQuery code where it only counts and styles cards within one section. If users input cards into multiple sections, the code fails to differentiate between them. For example, if there are 2 sections, the cards in the first section should be blue while the cards in the second section should be red. Currently, all cards are showing up as blue.
var numCard = $('.cards').length;
if (numCard == "2") {
/* $('.cards').css('color', 'red'); */
$("section .cards").parent().addClass("two-cards");
} else if (numCard == "3") {
$("section .cards").parent().addClass("three-cards");
} else {
$('section .cards').parent().addClass("four-cards");
}
body {
padding: 20px;
font-family: Helvetica;
}
.two-cards .cards {
color: red;
}
.three-cards .cards {
color: green;
}
.four-cards .cards {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
<div class="cards">
Third Card
</div>
<div class="cards">
Third Card
</div>
</section>
<p>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
</section>