如何使用jquery从表(网格)验证文本框值

时间:2012-06-08 04:08:59

标签: jquery

单击保存按钮时,我需要从生成的html表(网格)中验证文本框值。以下是我到目前为止的情况。我使用Firebug跟踪代码,它只循环第一行,但我需要循环从标记中的第二行开始的行。请帮忙。

Html代码

<div class="msg-body">
     <table class="dynamictable">
                <thead>
                    <tr>
                        <th style="display: none"></th>
                        <th>Package Name</th>
                        <th>Package Cost</th>
                        <th>No. of Attendees</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody>
                 <tr class="prototype">
                        <td style="display: none"><input type="hidden" name="id[]" value="" class="id" /></td>
                        <td><input type="text" name="packagename[]" value="" class="pkname" /></td>
                        <td><input type="text" name="packagecost[]" value="" class="pkcost"/></td>
                        <td><input type="text" name="noofattendees[]" value="" class="nfattendees"/></td>
                        <td>@Html.ActionImage("", null, "~/Content/Images/delete.gif", "Delete", new { @class = "deleterows" }) </td>
                 </tr>
                 <tr>
                    <td style="display: none"><input type="hidden" name="id[]" value="" class="id" /></td>
                    <td><input type="text" name="packagename[]" value="" class="pkname" /></td>
                    <td><input type="text" name="packagecost[]" value="" class="pkcost"/></td>
                    <td><input type="text" name="noofattendees[]" value="" class="nfattendees"/></td>
                    <td>@Html.ActionImage("", null, "~/Content/Images/delete.gif", "Delete", new { @class = "deleterows" }) </td>
              </tr>
           </tbody>
    </table>
     <div style="padding:20px 0 20px 100px "><input type="button" id="btnAddButton" value="Add New" class="button addbutton"/><input type="button" id="btnSaveRow" value="Save" class="button addbutton"/></div>
</div>

Javascript代码

 $("#btnSaveRow").click(function () {
        $('.dynamictable tr').each(function () {
            var $val = $("input[type='input']").val();
            if ($val == "") {
                alert("Please enter data");
                $(this).focus();
                return false;
            }
              return true;
        });

1 个答案:

答案 0 :(得分:2)

$("#btnSaveRow").click(function() {
    $("input[type='text']", ".dynamictable tbody tr:gt(0)").each(function() {
        if (!$.trim(this.value)) {
            alert("Please enter data");
            $(this).focus();
            return false;
        }
        return true;
    });
});

<强> DEMO