[jQuery]進階table搜尋法,運用parent,children,next,is等技巧(ex:必填欄位警告訊息alert)

  • 3453
  • 0
  • 2014-03-21

摘要:[jQuery]進階table搜尋法,運用parent,children,next,is等技巧(ex:必填欄位警告訊息alert)

這是管理資訊系統裡面常用的例子,抓出畫面上顯示為必填欄位的文字

並且偵測相對應的textbox或是下拉式選單是否為空,最後alert警告訊息該欄位必填。

基本運作原理:

針對某個table,loop跑他下面所有的物件,在抓出每個cssclass是lbl-notnull的span(asp:label)

然後抓出span下一個td儲存格的textbox或是dropdownlist

並偵測其value是否為空

下面是*.aspx


<asp:TemplateField>                 
                    <ItemTemplate>
                        <asp:CheckBox ID="chk" runat="server" />
                        <asp:HiddenField ID="hidamt" Value="<%# Eval("amt") %>"  runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

下面是javascript


var errorContent = ''            
$("table[id='tableEdit'] .lbl-notnull").each(function () {
                var lblText = $(this).text(); //先記錄label的文字
                var object = $(this).parent().next().children().each(function () {
                    if ($(this).is("input[type=text]")) {
                        errorContent += '\n囧:' + lblText;
                    }
                    if ($(this).is("select")) {
                        errorContent += '\n囧' + lblText;
                    }
                });

            });

            if (errorContent.length > 0) {
                errorContent = '以下欄位請勿空白:' + errorContent
                alert(errorContent);
                return false;
            }
            else {
                return true;
            }