Click a div to check / uncheck a checkbox

前端 未结 5 668
执念已碎
执念已碎 2020-12-11 19:13

I applied the following code to make table rows check/uncheck a child checkbox when clicked. Now I discovered that when clicking the checkbox itself inside the row it doesen

相关标签:
5条回答
  • 2020-12-11 19:34

    I have found that you can do this simply by wrapping the div in the label. It doesn't work if the content in the div is what you are trying to change though, but it will check the checkbox.

    0 讨论(0)
  • 2020-12-11 19:50

    What about:

    return false;
    

    As it is the same as entering both:

    e.preventDefault(); 
    e.stopPropagation();
    

    I believe that is the go to - no?

    0 讨论(0)
  • 2020-12-11 19:51

    Check the target of the caller is not a checkbox

    $("tr").live("click",function(event) {
        var target = $(event.target);
        if (target.is('input:checkbox')) return;
    
        var checkbox = $(this).find("input[type='checkbox']");
    
        if( checkbox.attr("checked") == "" ){
           checkbox.attr("checked","true");
        } else {
           checkbox.attr("checked","");
        }
    });
    

    DEMO http://jsfiddle.net/7Bze7/

    The code above checks that the sender of the event is not a checkbox.

    0 讨论(0)
  • 2020-12-11 19:52

    I suspect that the click event is bubbling from the checkbox to the tr. Try adding this code as well:

    $('tr input[type=checkbox]').click(function(e){
            e.stopPropagation();
    });
    

    EDIT

    here's an example: http://jsfiddle.net/GSqNv/

    0 讨论(0)
  • 2020-12-11 19:55

    Besides the given solutions, isn't it better to just set the checkbox to the oposite state? For example:

    var _current_state = checkbox.attr("checked");
    checkbox.attr("checked") = !_current_state;
    
    0 讨论(0)
提交回复
热议问题