I have a sample code:
<div class="box">
<div id="banks">
<ul>
<li class="active1">Bank1</li>
<li">Bank2</li>
</ul>
</div>
<div id="buttons">
<ul>
<li class="active2">USD</li>
<li>EURO</li>
</ul>
</div>
</div>
And jquery:
<script>
$(document).ready(function(){
$('.box li').click(function(){
$('#banks li').removeClass('active1');
$('#buttons li').removeClass('active2');
$(this).addClass('active1');
$(this).addClass('active2');
});
});
</script>
OUPUT: Error when click on:
<div class="box">
<div id="banks">
<ul>
<li class="active2 active1">Bank1</li>
<li class="active2">Bank2</li>
</ul>
</div>
<div id="buttons">
<ul>
<li class="">USD</li>
<li class="">EURO</li>
</ul>
</div>
</div>
How to using jquery exactly for add class for 2 id are (banks and buttons) with 2 class are (active1, active2)
The most common scenario is to add a class when you click on a menu link and want to make it active or highlighted. That is make the link active or inactive. For adding class in jQuery we use . addClass() method.
In Bootstrap 4, Javascript or jQuery events are used to add active class on click event in custom list group. Syntax: $(document). ready(function() { $('selector').
AS I understand you need to be able to choise single option in each section. Use only one active
class and change styles in css:
html:
<div class="box">
<div id="banks">
<ul>
<li class="active">Bank1</li>
<li>Bank2</li>
</ul>
</div>
<div id="buttons">
<ul>
<li class="active">USD</li>
<li>EURO</li>
</ul>
</div>
</div>
js:
$(document).ready(function(){
$('.box li').click(function() {
$(this).siblings('li').removeClass('active');
$(this).addClass('active');
});
});
css:
.box li { cursor:pointer; }
#banks .active { color:red; }
#buttons .active { color:blue; }
Code: http://jsfiddle.net/jn3v4/2/
$(document).ready(function(){
$(".active-class a").click(function() {
$(".active-class a").removeClass("active");
$(this).addClass("active");
});
});
a.active
{
background:#000000;
color:#ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
<ul>
<li class="active-class"><a href="#" class="active">home</a></li>
<li class="active-class"><a href="#">about</a></li>
<li class="active-class"><a href="#">gallery</a></li>
<li class="active-class"><a href="#">contact us</a></li>
</ul>
</div>
when removing the class you are looking only inside the #box
change it to .box
like
$('.box li').click(function(){
$('.box li').removeClass('active1');
$('.box li').removeClass('active2');
$(this).addClass('active1');
$(this).addClass('active2');
});
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With