Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.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
Javascript 单选按钮';消失';_Javascript_Jquery_Html_Radio Button - Fatal编程技术网

Javascript 单选按钮';消失';

Javascript 单选按钮';消失';,javascript,jquery,html,radio-button,Javascript,Jquery,Html,Radio Button,使用复选框,我想更改两个单选按钮的选中状态。这可以正常工作,但是当再次更改复选框时,单选按钮checked visual“消失”,而代码显示它已选中。这是怎么来的 演示: JS: HTML: 1 二 检查 更改javascript并使用prop而不是attr $("#change_radio").change(function () { console.log("change"); if ($(this).is(":checked")) { $("#one")

使用复选框,我想更改两个单选按钮的选中状态。这可以正常工作,但是当再次更改复选框时,单选按钮checked visual“消失”,而代码显示它已选中。这是怎么来的

演示:

JS:

HTML:

1
二
检查

更改javascript并使用prop而不是attr

$("#change_radio").change(function () {

    console.log("change");

    if ($(this).is(":checked")) {
        $("#one").attr("checked", false);
        $("#two").prop('checked', true);
    }
    else  {
        $("#two").attr("checked", false);
        $("#one").prop('checked', true);
    }
});
使用
$(“#一”).prop('checked',true)

而不是

$(“#一”).attr('checked','checked')


享受:)

不错,这很有效。你知道为什么在我的代码中,选中的会消失,而在更改时代码中仍然显示“选中”吗?请使用prop代替
attr
,添加一个解释并让我投票DJust发现这会删除代码中单选按钮上的checked=“checked”,因此它不会将值传递给我正在编码的url。编辑:用这个代码修复了它。不,单选按钮实际上是隐藏的,用复选框代替。我更喜欢
$(“#one”)。removeAttr(“选中”)
$(“#一”).attr(“选中”,假)。更好的方法是使用Anri回答中给出的
.prop(…)
。使用
$(“#one”).attr(“选中”,false)
使您的HTML类似于
checked
属性的存在,无论其值如何,(在某些浏览器中,Firefox,根据我自己的经验),都会使
复选框处于选中状态。
<input type="radio" id="one" name="test" checked="checked"><label for="one">one</label>
<input type="radio" id="two" name="test"> <label for="two">two</label>

<input type="checkbox" id="change_radio"> <label for="change_radio">check</label>
$("#change_radio").change(function () {

    console.log("change");

    if ($(this).is(":checked")) {
        $("#one").attr("checked", false);
        $("#two").prop('checked', true);
    }
    else  {
        $("#two").attr("checked", false);
        $("#one").prop('checked', true);
    }
});