[英]check if all input field has value jQuery condition
我有幾個輸入字段,其類名稱為required
。
我下面有一個代碼來檢查我所有的<input>
字段是否都有一個值,如果不為空或為null,它將顯示/取消隱藏特定的div
。
但它似乎並沒有對我起作用。
同樣,默認情況下,通過CSS, #print
顯示為none。
<!-- 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();
}
});
});
我建議:
$('#print').toggle(!($('input.required').length == $('input.required').filter(function () {
return this.value;
}).length));
顯然,這應該在#print
上運行,假設您只想在submit
之前顯示#print
元素作為驗證。
參考文獻:
正如我在上面的評論中所述,在用戶加載任何內容之前,您正在檢查頁面加載時的值。 如果頁面上有一個按鈕,請將事件綁定到將在適當的時間觸發該功能的事件。
有點像這樣的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();
}
});
嘗試
$(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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.