检查表数据是否有输入

时间:2016-07-12 03:59:28

标签: javascript jquery

我正在尝试检查我的表数据是否为空字段。我使用了$('td:has(input)'),因为我的所有单元格都有<input type="text" class="form-control">。如果用户点击保存按钮,我想要做的是检查所有文本字段是否为空,否则会提示消息。但是用户可以填充其中一个文本字段但不能留空。我怎样才能做到这一点?

表:

<div class = "col-md-12">

    <table class = "table" id = "customFields">

        <thead>
            <tr>
                <th>Stock No.</th>
                <th>Unit</th>
                <th class = "description">Description</th>
                <th>Quantity</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
            </tr>
        </tbody>

    </table>

    <button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
    <button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
    <button type = "submit" class = "btn btn-primary" id = "save">Save</button>

</div>

脚本:

<script>

    $(document).ready(function ()
    {
        $("#addMore").click(function ()
        {
            $("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
        });

        $("#removeRow").click(function()
        {   
            if ($('#customFields tbody tr').length== 1)
            {

                alert('Cannot be left blank');
            }
            else
            {
                $('#customFields tr:last').remove();
            }

        });

        $("#save").click(function ())
        {

            if ($('td:has(input)').text(function ()
            {

            }));

        });

    });


</script>

1 个答案:

答案 0 :(得分:0)

您可以使用form-control类遍历所有元素,并确保它们的组合值长度大于零。

$("#save").click(function (){
    var values = "";
    $.each($(".form-control"), function(i, c){
        values = values + $(c).val().trim(); // .trim() to remove white-space
    });
    if(values.length > 0)
    {
        //Success!
    }
    else
    {
        // Error!  
    }
});