只有第一个复选框值被添加到我的表中

Only the first checkbox value is being added to my table

本文关键字:我的 添加 第一个 复选框      更新时间:2023-09-26

无论我在复选框列表中选中了多少项,当我查看要添加行的表时,只有选中的第一个复选框的值会添加到我的表中。我试图遍历每个复选框并获取每个复选框的值以插入,但它似乎不起作用。知道我在哪里搞砸了吗?

在我的jquery中,我正在运行一个if语句,以防止在取消选中框时向表中添加未定义项。

下面是一个jsfiddle演示我正在做的事情:http://jsfiddle.net/22L9x006/

$(document).on('click', 'input:checkbox[name=certsToValid]', function() {
$newTableRow = '<tr><td><p>' + $('[name=certsToValid]:checked').val() + '</p></td><td><input type="text" placeholder="Credential #..." class="certInput" /></td><td><p>$5.00</p></td><td><div class="removeRow"></div></td></tr>';
$(this).attr('value');
if($.each($('input:checkbox[name=certsToValid]').is(':checked')) && $(this) != undefined) {
    $('.certSelections').append($newTableRow); 
}
});

我刚刚调整了您的Fiddle,以便将带有单击复选框值的选项添加到表中。调整是为了改变

$newTableRow = '<tr><td><p>' + $('[name=certsToValid]:checked').val() + ...

进入

$newTableRow = '<tr><td><p>' + $(this).val() + ...

这不是一个完整的解决方案,因为我猜你想在取消选中复选框时删除一行,目前每次点击复选框都会添加一个新行,但我认为你可以从这里开始解决。

目前尚不清楚您的目标是什么,但编写代码的正确方法是:

$(document).on('change', ':checkbox[name=certsToValid]', function() {
    $(this).filter(':checked').each(function() {
        $newTableRow = '<tr><td><p>' + this.value + '</p></td><td><input type="text" placeholder="Credential #..." class="certInput" /></td><td><p>$5.00</p></td><td><div class="removeRow">REMOVE</div></td></tr>';
        $('p:contains(' + this.value + ')','.certSelections tbody').length ||
            $('.certSelections tbody').append($newTableRow);
    });
});
$(document).on('click', 'div.removeRow', function() {
    $(this).closest('tr').remove();
});

演示

如果你能澄清你试图实现的目标,那么这个答案可以得到改进,以更好地指导你实现目标。

这里是PeterKA答案的扩展。代码与他的完全相同。我只是添加了一种"筛选"来避免重复的行。

 $(document).on('change', ':checkbox[name=certsToValid]', function () {
        $(this).filter(':checked').each(function () {
            $newTableRow = '<tr><td><p>' + this.value + '</p></td><td><input type="text" placeholder="Credential #..." class="certInput" /></td><td><p>$5.00</p></td><td><div class="removeRow">REMOVE</div></td></tr>';
            var optionValue = this.value;
            var added = false;
            $('.certSelections td:first-child p').each(function (index) {
                if ($(this).text() === optionValue) {
                    added = true;
                }
            });
            //only add if it's not found in the table  
            if (!added) {
                $('.certSelections tbody').append($newTableRow);
            }
        });
    });

Fiddle