Reputation:
$(".Button").click(function (e) {
e.preventDefault();
if (!$(this).hasClass("buttonActive")) {
$(this).addClass("buttonActive");
} else {
$(this).removeClass("buttonActive");
}
});
.buttonActive {
background: #100f10;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="numberSelect">
<button type="button" value="1" class="Button">1</button>
<button type="button" value="2" class="Button">2</button>
<button type="button" value="3" class="Button">3</button>
<button type="button" value="4" class="Button">4</button>
<input type="hidden" name="number" id="number">
</div>
What I wanna do is when I click on any button it checks if there is any other button has the class "buttonActive" and if any other button has this class it removes the class form the other button and add it to the button I clicked. So it should always be a single button which has the "buttonActive" class.
Upvotes: 2
Views: 83
Reputation: 15213
It is not necessary to check the existence of a class by the if { ... }
condition. This can be done in the jquery selector itself. Removing a class will affect only those selectors that contain this class, but not the current (this) selector:
...(".Button.buttonActive").not(this).removeClass("buttonActive");
There are several variations of the solution to your problem. But I want to offer a solution in one line, without conditions if.
$(".Button").click(function (e) {
e.preventDefault();
$(this).addClass("buttonActive").closest("#numberSelect").find(".Button.buttonActive").not(this).removeClass("buttonActive");
});
.buttonActive {
background: #100f10;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="numberSelect">
<button type="button" value="1" class="Button">1</button>
<button type="button" value="2" class="Button">2</button>
<button type="button" value="3" class="Button">3</button>
<button type="button" value="4" class="Button">4</button>
<input type="hidden" name="number" id="number" />
</div>
Upvotes: 0
Reputation: 1
You have to remove the class from all buttons first then add it to the clicked button like this:
$(".Button").click(function (e) {
e.preventDefault();
if (!$(this).hasClass("buttonActive")) {
$("button").removeClass("buttonActive");
$(this).addClass("buttonActive");
}
});
.buttonActive {
background: #100f10;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="numberSelect">
<button type="button" value="1" class="Button">1</button>
<button type="button" value="2" class="Button">2</button>
<button type="button" value="3" class="Button">3</button>
<button type="button" value="4" class="Button">4</button>
<input type="hidden" name="number" id="number">
</div>
Upvotes: 2