onclick for Bootstrap .btn-group checkbox works in JSFiddle but not browser

前端 未结 2 933
醉梦人生
醉梦人生 2021-01-26 09:07

The form below contains a Bootstrap toggle button group that uses checkboxes. I need to listen for click events on the checkbox inputs.



        
相关标签:
2条回答
  • 2021-01-26 09:10

    I can't explain why it is working in JSFiddle, however it looks like the checkbox is essentially hiding behind the button. Are you going to be submitting this form, or just doing some jquery to the page based on selection? If it were me and you want to keep the buttons you can do this:

    <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>
    
    0 讨论(0)
  • 2021-01-26 09:19

    I tried to interpret your question as best as I could. Here's my jsfiddle: https://jsfiddle.net/wqse25vj/ I hope it helps.

    The hardest part of being a programmer is asking questions. "A problem well-stated is a problem half-solved." holds true. If this is not the answer you were looking for, refine your question and be sure to ask again. As a general note: remember to encapsulate your jQuery code in $(document).ready() and continue experimenting & learning HTML, CSS and Bootstrap. For example, I noticed your HTML label tag missing a for attribute, and a repetition of class names on your divs and input fields (hint: the Bootstrap class is required for the div only.). All the best to you!

    Resources I used:

    • https://www.tutorialrepublic.com/faq/how-to-check-a-checkbox-is-checked-or-not-using-jquery.php
    • copy/pasted the inline-checkbox https://getbootstrap.com/docs/4.0/components/forms/
    0 讨论(0)
提交回复
热议问题