当某些字段和表数据为空时停止保存

时间:2014-10-14 01:52:45

标签: javascript jquery

在此代码中,如果任何表格单元格为空,则不允许保存,但是,我现在想要保存甚至最后一个表格单元格为空。

  

我如何在这里添加表格行的最后输入,其中类型不是   隐藏?

 $('#myTable tr input[value != add]:text').filter(function () {});

查看我的FIDDLE

这是我的javascript代码:

 $("#btnSave").click(function (event) {
        var flag = false;
        var emptyBoxes;
        var $rows = $('#myTable tr:not(:hidden)');
        $rows.each( function () {
            emptyBoxes = $('#myTable tr input[value != add]:text').filter(function () {
                return this.value == "";    
            });

            if (emptyBoxes.length != 0) {
                flag = true;
            }
        });
        if (flag) {
            alert("this cannot be empty");
            emptyBoxes.eq(0).focus();
        } else 
            alert("done");
    });

1 个答案:

答案 0 :(得分:2)

请尝试以下代码:

var fields = $('input[type=text]'); /* All fields */

/* This function will find empty fields */
var findEmptyFields = function() {

    var n = fields.length - 1;

    /* Go throw all inputs with type=text and if someone is empty return index of this element */
    for (var i = 0; i < n; i++) {
        if (fields.eq(i).val() === '') {
            return i;
        }
    };

    /* Else return false that means that we didn't find any empty fields*/
    return false;


}

$("#btnSave").on('click', function() {

    var empty = findEmptyFields();
    if (empty === false) {
        alert('Done');
    }
    else {
        alert('Some field is empty');
        fields.eq(empty).focus();
    }

});