2014-01-29 49 views
0

我還是比較新的使用jquery,我試圖阻止表單提交,如果記錄列表中的任何值的數量爲零,並顯示一個單一的消息,記錄的數量爲零。阻止表單提交併顯示錯誤消息

這是我到目前爲止有:

<script type="text/javascript"> 
    var j$ = jQuery.noConflict(); 

    j$(document).ready(function() { 
     j$('[id$=btnSubmit]').click(function(e){ 
      j$('[id$=documentQuantity]').each(function(index){ 
       if(j$(this).text() == '0') { 
        j$("#contentQtyError").css({"display":"inline"}); 
        j$(this).parent().parent().css({"background-color":"#FFFFCC"}); 
        e.preventDefault(); 
       } 
      }); 
     }); 
    }); 

</script> 

我拍攝的按鈕,點擊我還成功地被困如果列表中的一個值是零。如果其中一個值爲零,如何停止提交表單?我使用preventDefault()方法嗎?另外,如何在頁面上顯示一條消息,指出哪些行(記錄)是零數量的消息?突出顯示零數量的行是理想的。

感謝您的幫助!

+0

你應該綁定事件與表單提交 – Satpal

回答

0

VARĴ$ = jQuery.noConflict();

j$(document).ready(function() { 
    j$('[id$=btnSubmit]').submit(function(e){ 
     console.log('************** we clicked the submit button'); 
     j$('[id$=documentQuantity]').each(function(index){ 
      if(j$(this).val() == 0) { 
       console.log('************* value is zero'); 
       e.preventDefault(); //it will prevent the form submission 
       //below will display the warning message 
       j$(this).append("<span class='message'>this value can not be left blank</span>"); 
      } 
     }); 
    }); 
}); 
+0

我感謝所有的意見和幫助!它引導我找到一個很好的解決方案! – Dman100

0

您應該使用表單提交事件來執行驗證。無論是使用e.preventDefault();return false;防止默認動作

j$(document).on('submit', 'form#YourFormID', function (e) { 
    console.log('************** we clicked the submit button'); 
    j$('[id$=documentQuantity]').each(function (index) { 
     if (j$(this).val() == 0) { 
      console.log('************* value is zero'); 

      //To prevent form submission 
      return false; 
     } 
    }); 
}); 

注:在地方form#YourFormID'提供正確的選擇。如果您有單一的形式僅form就足夠

0

嘗試preventDefault

var j$ = jQuery.noConflict(); 

j$(document).ready(function() { 
    //Assuming you have only one form in the document, if not change the selector to be specific to the form you want to target. 
    j$('form').on('submit', function(e){ 
     console.log('************** the form is being submitted'); 
     j$('[id$=documentQuantity]').each(function(index){ 
      if(j$(this).val() == 0) { 
       console.log('************* value is zero'); 
       e.preventDefault(); 
      } 
     }); 
    }); 
}); 
相關問題