checkbox inside div. On click checked or unchecked using jquery 1.9.1

Tadeusz Majkowski picture Tadeusz Majkowski · Nov 16, 2013 · Viewed 20.9k times · Source

Hi i want to make checkbox checked or unchecked when i click div with text. Using jquery 1.9.1 here is a link to js fiddle

<div class="tel_show">
    <input type="checkbox" name="whatever" />
    &nbsp; visible
</div>

$("div.tel_show").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","");
    }
});

js fiddle link

Answer

Nelson picture Nelson · Nov 16, 2013

The use of .live() is deprecated on jQuery 1.9.x , also the use of checked html attribute to toggle checkboxes is deprecated, use .prop('checked') instead, your updated code should be:

$("div.tel_show").on("click",function(event) {
    var target = $(event.target);
    if (target.is('input:checkbox')) return;

    var checkbox = $(this).find("input[type='checkbox']");

    if( !checkbox.prop("checked") ){
        checkbox.prop("checked",true);
    } else {
        checkbox.prop("checked",false);
    }
});

see working fiddle