简体   繁体   中英

Clicking on label doesn't trigger click event

I have this code:

<label><input type="checkbox">True?</label>

and

$("label").click(function () {
  $(this).toggleClass("active");
});

When I click the checkbox class toggles, when I click "True?" nothing happens. Why?

Then if I don't wrap checkbox in label everything works fine.

<input type="checkbox" id="c1"><label for="c1">True?</label>

This is so weird... And it doesn't matter if I put "for" or not.

http://jsfiddle.net/zufs6ueh/1/

What is going wrong here?

This would be safer to use:

$(function() {

    $('input[type="checkbox"]').bind('change', function (v) {

        if($(this).is(':checked')) {
            $(this).parent().addClass('active');
        } else {
            $(this).parent().removeClass('active');
        }
    });

});

Using change instead of click allows for people that navigate forms using the keyboard.

You're really close @Andrey, some noteworthy things about HTML input s ;

  • Both radio and checkbox HTML type s can have an onclick call out to JavaScript

  • Both radio and checkbox HTML type s have the .checked property that maybe inspected by JavaScript and the :checked pseudo class within CSS

  • Using name s on radio HTML type s allows for grouping things

Here's some example code that does stuff with a checkbox ...

 /** * Example JavaScript function for HTML input radio or checkbox types to call * @returns {boolean} */ function checkCheckbox(checkbox) { if (checkbox.checked != true) return false; /* Do JavaSript things when checkbox is checked */ console.log('checkbox.checked -> ' + checkbox.checked); window.alert('checkbox.value -> ' + checkbox.value); return true; } 
 /** * Hide things that should not be seen by just anyone */ .menu__checkbox, .menu__container { display: none; visibility: hidden; opacity: 0; filter: alpha(opacity=0); /* Old MS compatibility */ } /** * Stylize the label some */ .menu__label { display: block; width: 20px; height: 100%; transform: rotate(90deg); } /** * Show some things when checkbox is checked * Note, if feeling adventurous try using a `~` instead of `+` */ .menu__checkbox:checked + .menu > .menu__container { display: block; visibility: visible; opacity: 1; filter: alpha(opacity=100); } /** * Oh and un-rotate label when checkbox is checked too */ .menu__checkbox:checked + .menu > .menu__label { transform: rotate(0deg); } 
 <input type="checkbox" class="menu__checkbox" value="valuable_checkbox" onclick="checkCheckbox(this);" id="trigger-menu"> <div class="menu"> <div class="menu__container"> <p class="menu__description"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> <label for="trigger-menu" class="menu__label"> &#x25B2; </label> </div> 

... if ya look real close, targeting via trigger-menu shared between the above label 's for and the input 's id is doing some things with CSS and HTML that many might resort to JavaScript to do... though placing the checkbox so far outside of the menu's scope was only for demonstration; just 'cause something can be done doesn't always mean should in other words.

Like I eluded to the question's code was really close...

<input type="checkbox" id="c1"><label for="c1">True?</label>

... probably would be functional with...

<input id="c1" type="checkbox" onclick="window.alert('this.checked -> ' + this.checked);">
<label for="c1">Is checked?</label>

And as I also hinted that radio type d input s could be use similarly, the following is a preview of something that may be made public one day within something ridiculous...

    <div class="menu__style">
      <input type="radio"
             name="colorize"
             value="Default"
             onclick="color_picker.unsetAlternateStyleSheet()"
             class="menu__style__item"
             id="style-default">
      <label for="style-default"
             class="menu__style__label">Default Style</label>
      <br>

      <input type="radio"
             name="colorize"
             value="AlternateStyleOne"
             onclick="color_picker.setAlternateStyleSheet(title = this.value)"
             class="menu__style__item"
             id="style-one">
      <label for="style-one"
             class="menu__style__label">First Alternative Style</label>
      <br>

      <input type="radio"
             name="colorize"
             value="AlternateStyleTwo"
             onclick="color_picker.setAlternateStyleSheet(title = this.value)"
             class="menu__style__item"
             id="style-two">
      <label for="style-two"
             class="menu__style__label">Second Alternative Style</label>
    </div>

Clicking the label also triggers a click on the input so bind the change event to the checkbox itself:

 $(function(){ $("label input").on("click",function(){ $(this).parent().toggleClass("active"); }); }); 
 .active {color:red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label><input type="checkbox" />True?</label> 

Or With CSS 3

If you don't need to support old browsers, you could use the :checked pseudo-class in CSS instead:

 input[type=checkbox]:checked + label {color:red;} 
 <input type="checkbox" id="demo" name="demo"> <label for="demo">True?</label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM