Reputation: 4539
I have the following jQuery to select and toggle a class on buttons, that i am selecting using two other classes. Why does the selector not complain, but does not change the classes? I have a fiddle here.
$(document).on('click', 'button.ajax-multi-btn', function(event) {
if ($(this).hasClass('ly')) {
$('button.ajax-multi-btn.ty').removeClass('secondary-menu-active');
$('button.ajax-multi-btn.ly').addClass('secondary-menu-active');
} else {
$('button.ajax-multi-btn.ty').addClass('secondary-menu-active');
$('button.ajax-multi-btn.ly').removeClass('secondary-menu-active');
}
});
I have the following HTML:
<button type="button" class="btn ajax-multi-btn ty secondary-menu-active">TY</button>
<button type="button" class="btn ajax-multi-btn ly">LY</button>
Upvotes: 0
Views: 25
Reputation: 564
In your FIDDLE the html markup does not have the buttons with class ajax-multi-btn
so the ones in your script won't work because it was selecting buttons that does not exist. Why not update your script to use the right classes?
see demo:
$(document).on('click', 'button.ajax-single-btn', function(event) {
if (!$(this).hasClass('ly')) {
$('button.ajax-single-btn.ty').removeClass('secondary-menu-active');
$('button.ajax-single-btn.ly').addClass('secondary-menu-active');
alert('ly');
} else {
$('button.ajax-single-btn.ty').addClass('secondary-menu-active');
$('button.ajax-single-btn.ly').removeClass('secondary-menu-active');
alert('ty');
}
});
.secondary-menu-active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn ajax-single-btn ty secondary-menu-active">
TY
</button>
<button type="button" class="btn ajax-single-btn ly">
LY
</button>
Upvotes: 0
Reputation: 4125
I changed your script on fiddle to work, you just have an error on the class you were using on the remove and add class functions.
$(document).on('click', 'button.ajax-single-btn', function(event) {
if (!$(this).hasClass('ly')) {
$('button.ajax-single-btn.ty').removeClass('secondary-menu-active');
$('button.ajax-single-btn.ly').addClass('secondary-menu-active');
alert('ly');
} else {
$('button.ajax-single-btn.ty').addClass('secondary-menu-active');
$('button.ajax-single-btn.ly').removeClass('secondary-menu-active');
alert('ty');
}
});
.secondary-menu-active {
color: red;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<button type="button" class="btn ajax-single-btn ty secondary-menu-active">
TY
</button>
<button type="button" class="btn ajax-single-btn ly">
LY
</button>
Upvotes: 1