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

21,297

Solution 1

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

Solution 2

use .prop() instead of .attr() and .live() is removed in 1.9, use .on() instead

$(document).on("click", "div.tel_show", function (event) {
    var target = $(event.target);
    if (target.is('input:checkbox')) {
        return;
    }
    var checkbox = $(this).find("input[type='checkbox']");
    checkbox.prop("checked", !checkbox.is(':checked'));
});

Demo: Fiddle

Share:
21,297

Related videos on Youtube

Tadeusz Majkowski
Author by

Tadeusz Majkowski

Updated on January 30, 2020

Comments

  • Tadeusz Majkowski
    Tadeusz Majkowski over 4 years

    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