The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs.

<html>
<head>
<title>Example: Bootstrap toggle button group</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.js"></script>
</head>
 
<body>
    <form role="form" id="form">
  <div class="form-group">
    <div>
      <div>
        <label for="fname">Name:</label>
      </div>
      <div id="fname" class="btn-group btn-group-toggle" data-toggle="buttons">
        <label class="btn btn-primary">
          a
          <input type="checkbox" value="a" name="fname">
        </label>
        <label class="btn btn-primary">
          b
          <input type="checkbox" value="b" name="fname">
        </label>
        <label class="btn btn-primary">
          c
          <input type="checkbox" value="c" name="fname">
        </label>
      </div>
    </div>
  </div>
</form>
 
    <script type="text/javascript">//<![CDATA[
$(function() {
   
 $('#fname input').click(function() {
          console.log('you clicked '+$(this).attr('value'))
          });

});
//]]></script>
  
  </body>
  </html>

To demonstrate this, I have added a listener that displays the checkbox value once selected:

$(function() {
    
  $('#fname input').click(function() {
    console.log('you clicked '+$(this).attr('value'))
  });

});

In a test environment like (JSFiddle), this works as intended - triggering the handler prints the checkbox value to the log with each selection.

However, upon running the page locally and making selections, the event doesn't fire, resulting in no output to the console. What could be causing this? The document matches the one from JSFiddle within an iframe, and has been tested on Chrome (v85) and Firefox (v78.0.2) without success.

Note: There's a 404 error linked to the result-light.css stylesheet during page load, but it seems inconsequential when removed.

Emphasizing the need to capture click events specifically, as opposed to using on('change'.

Note: It appears that Bootstrap styles the checkbox inputs with pointer-events: none;, potentially impacting the responsiveness of the click handler to browser queries. Attempts to switch this property to initial or inherit yielded no effects.


EDIT: Closing this inquiry since the issue stemmed from an oversight on my end. Upon review, realized that the browser script depended on Bootstrap 3.4.1 while JSFiddle utilized version 4.4.1.

It's likely that the reason for the lack of response in the browser was due to a segment called the Button data-API section available in Bootstrap 3.4.1's source code:

// BUTTON DATA-API
// ===============

if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
  // Prevent double click on radios, and the double selections (so cancellation) on checkboxes
  e.preventDefault()
  // The target component still receive the focus
  if ($btn.is('input,button')) $btn.trigger('focus')
  else $btn.find('input:visible,button:visible').first().trigger('focus')
}

This portion prevents double clicks on radios and multiple selections for checkboxes, absent in v4.4.1. Excluding this snippet from v3.4.1's source reestablishes expected functionality of the click handler.

If sticking with v3.4.1 is necessary, switching from click to focus will suffice, given radios and checkboxes retain focus. Refer to this JSFiddle for a demonstration.

Answer №1

I am unable to provide an explanation for why it is functioning as expected in JSFiddle, but it appears that the checkbox may be hidden behind the button. Are you planning to submit this form or are you just using jQuery to manipulate the page based on user selection? If it were up to me and you wish to retain the buttons, you can achieve this by:

<form role="form" id="form">
  <div class="form-group">
    <div>
      <div>
        <label for="fname">Name:</label>
      </div>
      <div id="fname" class="btn-group btn-group-toggle" data-toggle="buttons">
        <label class="btn btn-primary" data-value="a">
          a
        </label>
        <label class="btn btn-primary" data-value="b">
          b
        </label>
        <label class="btn btn-primary" data-value="c">
          c
        </label>
      </div>
    </div>
  </div>
</form>
        <script>
        $(function() {
    
  $('#fname label').click(function() {
    console.log('you clicked '+$(this).data('value'))
  });

});
        </script>

Answer №2

I made an attempt to understand your question to the best of my ability. Feel free to check out my jsfiddle for a possible solution: https://jsfiddle.net/wqse25vj/. I hope this provides some assistance.

One of the biggest challenges for programmers is formulating questions effectively. Remember, "A problem well-stated is a problem half-solved." If this response doesn't fully satisfy your query, try refining it and asking again. Always remember to include your jQuery code within $(document).ready() and keep exploring and honing your skills in HTML, CSS, and Bootstrap. For instance, I noticed that your HTML label tag was missing a for attribute, and there were duplicate class names on your divs and input fields (hint: the Bootstrap class is necessary for the div only). Best of luck!

Here are the resources I referred to:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which kinds of data are ideal for storage within the Vuex (Flux) pattern?

Currently delving into the world of Vuex for the first time as I develop an application in Vue.js. The complexity of this project requires a singleton storage object that is shared across all components. While Vuex appears to be a suitable solution, I am s ...

Apparent malfunctions in Bower packages

Here are some of the packages available on bower: bootstrap-ui, angular-ui-bootstrap, and angular-ui-bootstrap-bower. It appears that only angular-ui-bootstrap-bower has built js files. Can anyone provide more information on this? ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Modify the class name of the clicked button and another button when a button is clicked in ReactJs

I have a React component that displays two buttons. When the user clicks on the left button, it should change the class of both buttons and render the ListView component. Similarly, when the user clicks on the right button, it should change the class of bo ...

JavaScript: AWS Amplify: Retrieving the User ID (Sub ID) Following User Registration. Post Registration, Not to Be Confused with Sign In

Currently, I am utilizing the authentication module from AWS Amplify. One question that has been on my mind is how to obtain the userID once a user signs up. While it is possible to retrieve the ID after a user signs in, I am specifically interested in re ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

.htaccess causing issues with Ajax when rewriting URLs

After setting up the basic project and configuring htaccess for URL rewriting, I also implemented jQuery AJAX. Options +FollowSymLinks RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f Rewri ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

What is the method for configuring Vue to utilize a value other than the value property in form fields?

I am facing a unique challenge. Consider this: <select name="screw[type]" v-model="form.screw.type"> <option value="My value" ><?php _e('My value', 'fiam'); ?></option> //[...] Now, in another part of my ...

Is there a delay in Javascript identifying user existence when retrieving values from ajax?

I'm working on a script that checks if a username already exists before allowing a visitor to proceed. Here's a snippet of the code I'm using: EDIT: I've made some adjustments based on your feedback, but I'm still having trouble g ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

Ensuring uniqueness in an array using Typescript: allowing only one instance of a value

Is there a simple method to restrict an array to only contain one true value? For instance, if I have the following types: array: { value: boolean; label: string; }[]; I want to make sure that within this array, only one value can be set to t ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

The map failed to display any information

<div> {!props.isLoading && <div> {normalizedData.map((outerObj,index) => { { <p className="space_name"> {outerObj.space_name} </p> ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

The position of the HTML class shifts when the window is resized

I am in the process of creating a basic website layout that resembles this design. However, I am facing an issue where the webpage does not adapt well to different window sizes. Specifically, the elements with the classes .gameInfo and .playerList overlap ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Include money symbols within input fields with padding and vertical alignment

I am looking to create an input field that includes either € or $ currency symbols. The challenge is ensuring perfect vertical centering inside the input, especially when using padding. Is there a foolproof method to achieve this? https://i.stack.imgur ...

Looking for suggestions on how to bring this idea to life

I'm searching for a solution using JavaScript, jQuery, or Angular. I've created three random arrays like this: for example: (The values are randomly generated from the array ['member', 'medical', 'rx', 'disabi ...

"Enhancing Shopify experience by seamlessly adding products without the need for page refresh

Welcome to my first post on this platform. I recently implemented a list of products in my Shopify mini cart, and although the products are successfully added to the cart, clicking "add to cart" redirects me to the cart page. Is there a way to add products ...