如果输入为空,则取消选中行复选框

Uncheck row checkbox if inputs are empty on blur?

本文关键字:复选框 取消 输入 如果      更新时间:2023-09-26

我这里有两个问题。单击行上的输入将选中该行的复选框。目前,由于.prev()的原因,只有第一个文本输入会选中复选框。有别的方法吗?该行的所有输入都应该选中该行的复选框。

// check checkbox for clicked row
            $('table').on('click', 'input[type=text]', function () {
                $(this).closest('td').prev().find('input').prop('checked', true);
            });

同样,第二段代码没有正常工作。如果您关注的是另一行,如果来自前一行(或任何一行)的文本输入为空,请删除复选框。复选框将被保存,保存空白文本输入是没有意义的。

// remove check in inputs are empty for that row
            $('input[type=text]').blur(function () { 
                $('table tr').each(function () {
                    if ($(this).find('input[type=text]:empty').length()) {
                        $('td').find('input').prop('checked', false);
                    }
                });
            })
http://jsfiddle.net/Ldge5qzn/

找到最近的tr,然后找到作为复选框的输入并设置checked属性

$(this).closest('tr').find('input[type=checkbox]').prop('checked', true);

对于第二部分,:empty选择器针对具有子元素的元素进行测试,而不是针对空值进行测试,因此也必须进行修改。循环遍历每一行文本输入,如果其中任何一行不为空,设置一个标志。相应设置复选框

$('table tr').each(function () {
    var emptyRow = true;
    $(this).find("input[type=text]").each(function(){
        if($(this).val().length > 0) {
           emptyRow = false;   
        }
    });        
    if (emptyRow) {
        $(this).find('input[type=checkbox]').prop('checked', false);
    }
});

JSFiddle演示

你可以通过检查最近的tr -然后在tr

中找到复选框来做到这一点
$('table').on('click', 'input[type=text]', function () {
    $(this).closest('tr').find('input[type=checkbox]').prop('checked', true);
});

与第二个问题相同-使用最接近的tr

检查

然后你可以使用过滤器来获取所有值为

的文本输入

然后检查长度以查看是否有任何返回的输入-并使用.prop('checked',function()

设置相应的checked属性
$('input[type=text]').blur(function () {
    var $tr = $(this).closest('tr'); // get closest tr
    // get all of input[type=text] with value in that row
    var inputsWithValue = $tr.find('input[type=text]').filter(function () {
        return $.trim(this.value).length;
    });
    // set the checked to true if any element has value - else set checked to false
    $tr.find('input[type=checkbox]').prop('checked', function () {
        return inputsWithValue.length;
    }).length;
});

小提琴

看看这个,希望对你有帮助。

$('table').on('click', 'input[type=text]', function () {
                $(this).closest('td').parent('tr').find('input[type="checkbox"]').prop('checked', true);
            });

完整代码如下:-

JSFiddle