Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JQuery复选框失败(为什么不更改“checked”attr?)_Jquery_Checkbox - Fatal编程技术网

JQuery复选框失败(为什么不更改“checked”attr?)

JQuery复选框失败(为什么不更改“checked”attr?),jquery,checkbox,Jquery,Checkbox,我想根据用户单击编辑复选框来切换表单的禁用/启用状态。简单的东西 禁用组件工作时,复选框的默认选中行为将被覆盖。我甚至试着返回attr(“checked”,true)让它工作,但没有骰子。我假设这可能与我的标记有关(将复选框放在div中)。我想不出来 $(function(){ $('#target :input').attr('disabled','disabled'); $(':checkbox').toggle( function(){ $(this).attr(

我想根据用户单击编辑复选框来切换表单的禁用/启用状态。简单的东西

禁用组件工作时,复选框的默认选中行为将被覆盖。我甚至试着返回attr(“checked”,true)让它工作,但没有骰子。我假设这可能与我的标记有关(将复选框放在div中)。我想不出来

$(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);


});
});
谢谢,
Brendan更改
$(this).attr(“选中”,为真)
$(this).attr(“选中”、“选中”)

尝试
$(this).attr('checked','checked')
检查它,并
$(this.removeAttr('checked')
取消选中它。

是的,您可能认为应该具有值true或false的属性,倾向于将属性名称用作值,如下所示:

checked="checked"
disabled="disabled"

有些浏览器会接受checked=“true”,但这绝对不是最佳做法。

我想我找到了你的解决方案-看看这个问题


jQuery toggle似乎不能很好地处理复选框。

正如@Devbook.co.uk所指出的,该方法破坏了复选框的默认行为

一种解决方案是使用
.change()
事件以及复选框的
this.checked
属性

示例:

试试这个:

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


这对我的工作很有效。

是的,所以我以前尝试过(以及其他一些组合)。它不起作用。我只是再试了一次,但还是没有成功。由于将复选框放在div中,这可能是一个标记问题吗?很有趣。实际上,
.toggle()
事件会破坏它。它必须执行
返回false
事件。preventDefault
。编辑:看起来是这样的:是的,Devbook,我也有这种感觉。我试图通过返回$(this.attr(“checked”:“checked”)来绕过它,但我想这不会覆盖切换自然实现的返回false。谢谢你的确认
$(this).prop('checked', false);
$(this).prop('checked', true);