Reputation: 31
I want to use Bootstrap 4 buttons to indicate user choices on a page. The buttons should toggle selected/unselected and I'll need to be able to read their state as they're changed. I'm using on('click') to collect the state of the buttons. The results seem like I've got a timing issue. When a button is clicked it accurately reports the settings of all the buttons except the one clicked. A separate button setup just to report the button states always reports correctly. How do I correctly acquire the button states when one of the buttons have been pressed?
function showSelection() {
jQuery("#selection_display").empty();
jQuery("#selection_display").append("<hr>choice1 active:" + jQuery("#choice1").hasClass('active'));
jQuery("#selection_display").append("<hr>choice2 active:" + jQuery("#choice2").hasClass('active'));
jQuery("#selection_display").append("<hr>choice3 active:" + jQuery("#choice3").hasClass('active'));
}
jQuery(document).ready(function () {
jQuery(".option_group1").on("click", function () {
showSelection();
});
});
<button id="choice1" data-toggle="button" class="btn btn-secondary option_group1">choice1</button>
<button id="choice2" data-toggle="button" class="btn btn-secondary option_group1">choice2</button>
<button id="choice3" data-toggle="button" class="btn btn-secondary option_group1">choice3</button>
<button onclick="showSelection();">Update Selection</button>
<div id="selection_display">
</div>
https://jsfiddle.net/johnnyruin/peo81svu/35/
Upvotes: 2
Views: 2517
Reputation: 3825
This is because the bootstrap click
event was executed after your click
event, the classes of those buttons haven't been updated yet.
You can update the classes by yourself, to get it shown in your indicators correctly, and turn it back to let bootstrap
handle it:
jQuery(document).ready(function () {
jQuery(".option_group1").on("click", function () {
// update the class manually, to get it shown correctly
jQuery(this).toggleClass('active')
showSelection();
// turn it back to let bootstrap handle it
jQuery(this).toggleClass('active')
});
});
See this fiddle: https://jsfiddle.net/erqm4avj/
Here I am adding another solution using Bootstrap's API:
jQuery(document).ready(function () {
jQuery(".option_group1").on("click", function (e) {
// Stop bootstrap's event
e.stopPropagation();
// Change the state manully
jQuery(this).button('toggle');
// do whatever we want with the right states
showSelection();
});
});
See this fiddle: https://jsfiddle.net/Ln9yrjpx/
Upvotes: 1