2013-10-24 114 views
0

我正在處理向表格添加動態表格行的表格我已經對其進行了一些驗證,對我來說工作正常,但現在我面臨着一個新的挑戰,我希望驗證將在每一行上動態添加的文本框,但問題是我只想驗證該文本框時,其前面的其他文本框不是空的 ,我卡在這裏。我知道我可以爲每個進入該ID的元素使用.each(),但我不知道如何綁定該驗證行中的每個文本框,因爲當最後一個文本框(「我需要驗證「)不是空的,如果所有的文本框不是空的,那麼它不會給出任何錯誤。在jQuery中對動態添加的表格行進行驗證

這裏是我的驗證代碼:

if($('[id^="invoice_"]').val() =="" || $('[id^="invoice_"]').val() ==null || $('[id^="invoice_"]').val() ==0){ 
    alert("Invoice Number Cannot Be Empty"); 
    $("#savetodb").attr("disabled", "disabled"); 
    console.log("1"); 
    return false; 
}else{ 
    console.log("2"); 
    $("#savetodb").removeAttr("disabled");  

回答

1

以及你不需要爲每個輸入加法選擇...嘗試使用循環

$.each($('[id^="invoice_"]'),function(i,v){ 
    if(this.value=="" || this.value==null || this.value=="0"){ 
     alert("Invoice Number Cannot Be Empty"); 
     $("#savetodb").prop("disabled", true); 
     console.log("1"); 
     return false; 
    }else{ 
     console.log("2"); 
     $("#savetodb").prop("disabled", false); 
    } 

和是的,這必須是內你的提交函數,並應添加所有輸入後調用。 recommned使用prop(),如果您有最新版本的使用的jQuery(即1.6+)

+0

感謝您的答案,但它會爲我工作,就像我想驗證(「INVOICE_NUMBER」)時,在該行的每個文本框不EMP ty 例如: if(this.value ==「」|| this.value == null || ()#=「」&& $(「 ()!=「」) – user2274075

0

試試這個: 也許它會幫助你...

代碼方面(的.cs頁):

 string str = ""; 
     str = "<table>"; 
     for (int i = 1; i <= 5; i++) 
     { 
      str = str + "<tr><Label id='lbl" + i.ToString() + "' runat='server'>Lable " + i.ToString() + "</Label>"; 
      str = str + "<input type='Text' id='txt" + i.ToString() + "' onblur='checkValidation(this);'/></tr><br /><br />"; 
     } 
     str = str + "</table>"; 
     Response.Write(str); 

設計方(.aspx頁):

<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script type="text/javascript" language="javascript"> 
     function checkValidation(ctrl) { 
      var returnNow = false; 
      var i = 0; 
      $('input[type=text]').each(function (index) { 
       if (ctrl.id == this.id) { 
        if ($(this).val() == '' || $(this).val() == null) { 
         alert('enter some val for Label ' + (index + 1).toString()); 
        } 
        return false; 
       } 
       else { 
        if ($(this).val() == '' || $(this).val() == null) { 
         alert('Enter some value for Label ' + (index + 1).toString()); 
         return false; 
        } 
        else { 
         returnNow = true; 
        } 
       } 
      }); 
     } 
</script>