2013-09-30 347 views
0

我有幾個輸入字段的類名爲required檢查所有輸入字段是否有值jQuery條件

我有一個代碼如下,以檢查我的所有<input>字段是否有值,如果不爲空或爲空,它將顯示/取消隱藏特定的div

但它似乎對我有效。

此外,默認情況下,#print通過CSS顯示爲無。

<!-- index.php --> 

<input type="text" id="getID" class="required form-control" placeholder="id"> 
<input type="text" id="getName" class="required form-control" placeholder="name"> 

<!-- script.js --> 

$(document).ready(function() { 
    $('input.required').each(function() { 
    if($(this).val() != "") { 
     $("#print").show(); 
    } 
    else { 
     $("#print").hide(); 
    } 
    }); 
}); 
+2

您還沒有給出任何輸入值和驗證運行'$(document).load()',你可以嘗試將它綁定到'click'或者'submit'事件inst ead –

回答

0

嘗試

$(document).ready(function() { 
    //the default state 
    var valid = true; 
    $('input.required').each(function() { 
     //if the value of the current input is blank then the set is invalid and we can stop the iteration now 
     if ($.trim(this.value) == '') { 
      valid = false; 
      return false; 
     } 
    }); 
    //set the visibility of the element based on the value of valid state 
    $("#print").toggle(!valid); 
}); 
2

我建議:

$('#print').toggle(!($('input.required').length == $('input.required').filter(function() { 
     return this.value; 
    }).length)); 

Simplified JS Fiddle demo

顯然這應該在submit上運行,假設您只想在提交之前顯示#print元素作爲驗證。

參考文獻:

1

正如我在上面的評論中指出的那樣,當用戶有機會輸入任何內容之前,您正在檢查頁面加載時的值。如果您的頁面上有按鈕,請將事件綁定到將在正確的時間觸發該功能的事件。

東西有點像這樣jFiddle

的index.php

<input type="text" id="getID" class="required form-control" placeholder="id"> 
<input type="text" id="getName" class="required form-control" placeholder="name"> 
<div id="button">Submit</div> 
<div id="print">You're missing something D:!</div> 

的script.js

$('#button').on('click', function() { 
    $('#print').hide(); 
    var error=false; 
    $('input.required').each(function() { 
     if($(this).val() == "") { 
      error=true; 
     } 
    }); 
    if(error) { 
     $('#print').show(); 
    } 
}); 
+1

但是檢查是在每個內部,因此根據最後輸入驗證#print div將可見 –

+0

已編輯,注意到第二個我將它放入小提琴中:P –