我需要检查一个检查箱的检查财产,并使用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>

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


当前回答

我正在使用 jQuery 1.11.1 并且我也遇到设置和阅读检查箱值问题。

我终于通过这两个功能解决了它:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

它可能看起来有点脏,但它解决了我在不同类型的浏览器中所有的电缆问题。

其他回答

以点击进行检查或未检查的检查框进行操作。

$('#customCheck1').click(功能() { if (this.checked) { console.log('checked'); } 其他 { console.log('un-checked'); } ); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="customCheck1">

编辑: 如果(boolean = = 真实)虽然.checked 属性可能会返回其他类型的变量。

最好使用.prop(“检查”),它只会返回真实和虚假。

我发现这种方法是有用的;它返回了一系列检查的检查盒,然后你可以使用它们的值(这个解决方案使用jQuery):

// This is how you get them
var output = "";
var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
if(checkedBoxes.length <= 0) {
    alert('Please select check boxes');
    return false;
};

// And this is how you use them:
checkedBoxes.each(function() {
    output +=  this.value + ", ";
};

打印“输出”将为您提供您价值的单独列表。

事实上,我更喜欢改变事件。

$('#isAgeSelected').change(function() {
    $("#txtAge").toggle(this.checked);
});

饰 Fiddle

塞特:

$("#chkmyElement")[0].checked = true;

吉特:

if($("#chkmyElement")[0].checked) {
   alert("enabled");
} else {
   alert("disabled");
}

我这样做的方式就是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}