2013-02-12 19 views
0

我有多個輸入的形式,它被髮送之前,我檢查所有的輸入是空的:得到所有空的輸入和每個存儲在獨特的可變

<input type="text" name="number" id="number" style="float:left;clear:both;"/> 
    <input type="text" name="road" id="road" style="float:left;clear:both;" /> 
    <input type="text" name="town" id="town" style="float:left;clear:both;" /> 
    <input type="submit" name="submit" value="submit" id="submit" /> 

的jQuery:

$('#submit').on('click', submitForm); 
function submitForm(){ 
    if($('#number, #road, #town').val() ==''){ 
     $('#error-box').show(); 
     $('#error-box p').text('not all fields are complete - please complete to progress'); 
     return false; 
    } 
    else{ 
     alert('part 1 complete OK'); 
     $('#add-listing-part1').hide(); 
     $('#add-listing-part2').show(); 
     return false; 
    } 
} 

我想在錯誤框中顯示哪些字段是空的(用戶友好的消息很好),但我不確定如何在沒有加載if()語句的情況下最有效地執行此操作?

沿的線邏輯:

  1. 檢查,如果任何字段是空
  2. 如果「鎮」爲空在一個變量,存儲「鎮」,如果「道路」是空..等
  3. 在錯誤框文本更改爲類似 - 「不是所有的字段都完成後,請填寫$鎮和$路......」
+2

我建議你在試圖推出自己的定製解決方案之前嘗試[jQuery validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)插件。 – 2013-02-12 20:42:55

回答

0

您可以使用此代碼:

function submitForm() { 
    var empty = $('form input[value=""]'); 
    if (empty.length > 0) { 
     $('#error-box').show(); 
     empty.each(function (index, element) { 
      $('#error-box p').text($('#error-box p').text() + $(this).attr('name') + ' '); 
     }); 
     $('#error-box p').text($('#error-box p').text() + 'fields are not filled'); 
    } else { 
     // complete your submit 
    } 
}