我需要检查一个检查箱的检查财产,并使用jQuery进行检查财产的操作。

例如,如果年龄检查框被检查,那么我需要显示一个文本框进入年龄,否则隐藏文本框。

但下列代码默认返回虚假:

如果($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } 其他 { $("#txtAge").hide(); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none"> 年龄 已选择 </div>

如何成功查询已检查的房地产?


当前回答

使用:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

$(“#planned_checked”).change(函数() { if($(this).prop('checked')) { alert(“Checked Box Selected”); } other { alert(“Checked Box deselect”); } }; <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" name="planned_checked" checked id="planned_checked">

其他回答

我有相同的问题,没有一个发布的解决方案似乎工作,然后我发现这是因为ASP.NET将检查箱控制作为一个SPAN与INPUT内部,所以检查箱 ID实际上是一个SPAN的ID,而不是一个INPUT,所以你应该使用:

$('#isAgeSelected input')

而不是

$('#isAgeSelected')

然后,上面列出的所有方法都应该工作。

如果您需要使用 CSS 类作为 jQuery 选择器,您可以执行以下操作:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

它也适用于检查箱和无线电盒。

有很多方法可以检查一个检查箱是否被检查:

如何使用 jQuery 查看

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

查看例子或文档:

http://api.jquery.com/attr/ http://api.jquery.com/prop/

由于 jQuery 1.6, jQuery.attr() 的行为已经改变,用户被鼓励不要使用它来恢复一个元素的检查状态。

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

另外两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}