Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

I've an another version of the answer that's identical to the other two, but as it's a beginner question, I'm adding some better practices for newcomers to consider.

$('.tel_show').click(function( e ) { // emulate label on checkbox container
    if ( $(e.target).is('input[type="checkbox"]') ) return;

    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});

Why:

  • on is not needed (and marginally slower than click) when assigning to single element. It also helps when reading code to quickly determine the event is assigned to one single element (otherwise you would use $('.parent').on('click','.children',function(){/*...*/}))
  • initial selector does not need - and again is faster without - the meaningless div prefix.
  • no point in having obvious intermediate single-use variables
  • make use of jQuery API for prop instead of inventing own ways to do common stuff
  • selectors :checkbox and [type="checkbox"] are equivalent, I chose the latter as it performs better on new browsers, but that's trivial and you can use whichever
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top