JQuery checkbox fail (why won't it changed "checked" attr?)

I want to toggle disabled/enabled for a form based on a users click of an edit checkbox. Simple stuff.

While the disabling component works, the checkbox's default checked behavior is overriden. I even tried to return attr("checked",true) to get it to work but no dice. I'm assuming that this might have to do with my markup (placing the checkbox in a div). Can't figure it out.

$(function(){
$('#target :input').attr('disabled','disabled');

$(':checkbox').toggle(
    function(){
        $(this).attr("checked",true);
        $('#target :input').attr('disabled',false);

    },
    function(){
        $('#target:input').attr('disabled','disabled');         
        $(this).attr("checked", false);


});
});

Thanks, Brendan

Answers


As @Devbook.co.uk noted, the toggle-event[docs] method breaks the default behavior of the checkbox.

One solution is to use the .change() event, along with the this.checked property of the checkbox.

Example: http://jsfiddle.net/Efpr6/

$('#target :input').attr('disabled', 'disabled');

$('#toggler').change(function() {
    $('#target :input').attr('disabled', !this.checked);
});

Try $(this).attr('checked', 'checked') to check it and $(this).removeAttr('checked') to uncheck it.


Change $(this).attr("checked",true); to $(this).attr("checked","checked");


Yes, the attributes that you may think should have the value true or false, tend to have the attribute name used as the value, like this:

checked="checked"
disabled="disabled"

Some browsers will accept checked="true", but it's definitely not best practice.


Think I found your solution though - have a look at this question

Jquery toggle event is messing with checkbox value

Seems jQuery toggle doesn't play nice with checkboxes.


Try this:

$(this).prop('checked', false);
$(this).prop('checked', true);

See this: http://bugs.jquery.com/ticket/10248

this worked to my.


Need Your Help

How to use Application.LoadFromSQLServer in Window authentication

c# sql-server-2008 ssis

I want to load ssispackages programatically.I am using Application.LoadFromSQLServer