On my web page I have panels which contain various input widgets, some of which are Bootstrap button groups. The basic HTML for these looks similar to this:
<div class="btn-group btn-group-justified param-widget param-widget-buttongroup">
<div class="btn-group" role="group">
<button type="button" class="btn">Option A</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn">Option B</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn">Option C</button>
</div>
</div>
The panels of inputs are generated via Knockout templates, and are shown or hidden depending on which menu item the user selects in a main menu tree. This is done using jQuery's addClass()
and removeClass()
to add or remove the hide
class that's present in Bootstrap/AdminLTE. In both cases this class is just defined as display: none !important
.
I have jQuery code that performs tasks when the user provides input. For the buttons, it looks like this:
$(".param-widget-buttongroup .btn-group button").on("click", function()
{
// Do some stuff here - send messages to the device I'm controlling, etc.
});
This is done after the Knockout data bindings are applied. It definitely used to work, and still does for my other non-buttongroup inputs - however, at some point in the last month or so of development it's stopped working, and I'm currently trying to work out why.
If I place a console.log()
in the click handler function, nothing is printed when the button is clicked. However, reporting $(".param-widget-buttongroup .btn-group button").length
at the point when I'm attempting to add the click handler returns a count of 152 (ie. all the buttons across all the panels), so the buttons are definitely being found.
I've eventually determined that if I execute $(".param-widget-buttongroup .btn-group button").on("click", function(){ console.log("Button pressed"); })
in the Chrome web console, I only actually see this on click if the button's panel is visible at the time I attach the handler. Buttons whose panels are not visible do not get that handler set on them, even though the number of buttons found by the selector is still reported as 152. Once the handler is attached, however, I can show a different panel and come back to the original one later, and the expected output will still be printed on click.
Is there any reason jQuery would decide not to attach the click handler if the item is hidden at the time? I've not had this issue with any of the other inputs I'm using (single buttons, text boxes, select boxes, ion range sliders, ...).
Alternatively, is there a way I can definitively check what click handler an element currently has? I've tried checking the $(...)[0].onclick
value of the element, but regardless of whether the jQuery handler was attached successfully or not, this value is always null.