隐藏输入未正确选择的自定义复选框.Javascript需要调整

Custom checkbox with hidden inputs not selecting properly. Javascript needs adjusting

本文关键字:Javascript 复选框 调整 自定义 输入 选择 隐藏      更新时间:2023-09-26

我正在使用自定义复选框,input隐藏在span中;我已经编写了一个脚本来添加checked类,但它实际上并没有将输入标记为选中。 我在这里做错了什么?

更新:所以复选框现在检查! 万岁。 一个新的问题是,隐藏复选框上的可见性,在复选框区域选中时也会隐藏新类......如果单击标签,则复选框显示为选中,但如果单击复选框图像本身,则不会有任何变化...

.HTML

<fieldset>
  <label class="sublabel" title="Insights & Planning" for="checkbox-insights-and-planning">Insights & Planning</label>
  <span class="open-checkbox">
     <input id="checkbox-insights-and-planning" class="key-areas-checkbox" name="key-areas-of-interest" type="checkbox" />
  </span>
</fieldset>

.CSS

.open-checkbox {
    background-position: -4px -48px;
    background-image: url(../images/adcolor-sprite.png);
    background-repeat: no-repeat;
    cursor: pointer;
    display: block;
    float: right;
    height: 25px;
    margin-top: 10px;
    width: 25px;
}
.checked {
    background-position: -4px -12px;
    background-image: url(../images/adcolor-sprite.png);
    background-repeat: no-repeat;
    cursor: pointer;
    display: block;
    float: right;
    height: 25px;
    margin-top: 10px;
    width: 25px;
}
input[type=checkbox] {
    visibility: hidden;
}
#key-areas-inputs label.sublabel {
    display: block;
    float: left;
    height: 44px;
    padding: 0 0 0 10px;
    width: 300px;
}
#key-areas-inputs input.key-areas-checkbox {
    float: right;
    display: block;
    clear: none;
    height: 22px;
    width: 22px;
    margin-top: 18px;
    margin-right: 4px;
    margin-bottom: 0px;
    margin-left: 0px;
}
#key-areas-label {
    font-family: "Futura W01 Bold", Arial, Helvetica, sans-serif;
    font-size: 16px;
    color: #df007c;
    display: block;
    clear: left;
    float: left;
    width: 348px;
    margin-top: 50px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    padding-top: 0px;
    padding-right: 30px;
    padding-bottom: 0px;
    padding-left: 0px;
    text-align: right;
}

.JS

// check checked boxes on load     
    $(".key-areas-checkbox:checked").each(function(){
        $(this).next().addClass('checked');
    });
    // add class and checked attribute to filter inputs
    $('.open-checkbox').click(function () {
        console.log('click');
        var $this = $(this);
        var $input = $this.find('input');
        $this.toggleClass('checked', $input.is(':checked'));
        return;
        if($input.prop('checked')){
            $this.removeClass('checked');
        } else {
            $this.addClass('checked');
        }
    });

要选中复选框添加:

 $input.attr('checked','checked');

要取消选中:

$input.removeAttr('checked');

您的forid不匹配。将您的id更改为"复选框-见解和计划"(缺少"s"),它应该可以工作。

还要确保您的图像路径正确(我们无法用您的示例代码进行测试,因为它是相对路径;我只是用背景色尝试了一下,它奏效了)。

我想出了问题所在。 JS很好。 解决方法是将inputs嵌套在label内并包裹在div.内 这给出了预期的效果。