簡體   English   中英

如果輸入模糊時為空,請取消選中行復選框?

[英]Uncheck row checkbox if inputs are empty on blur?

我這里有2個問題。 單擊行上的輸入應選中該行的復選框。 當前,由於.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()

$('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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM