我想選擇所有輸入(文本框)在我的窗體中有需要的類和沒有價值。所以我使用:使用數值屬性選擇所有輸入
$('input[value=""]', '.required')
我的問題是,即使用戶輸入在文本框中的值時,VAL()返回值,但價值仍是空的,所以我上面的jQuery還是選擇了所有輸入中的哪以前是空的,它不應該。我如何選擇val爲空的所有輸入?
我想選擇所有輸入(文本框)在我的窗體中有需要的類和沒有價值。所以我使用:使用數值屬性選擇所有輸入
$('input[value=""]', '.required')
我的問題是,即使用戶輸入在文本框中的值時,VAL()返回值,但價值仍是空的,所以我上面的jQuery還是選擇了所有輸入中的哪以前是空的,它不應該。我如何選擇val爲空的所有輸入?
輸入的value attribute
和value property
在用戶編輯後不相同。
使用filter()
並檢查值屬性...喜歡的東西:
var $empties = $('input[required]').filter(function(){
return !this.value;
}).doSomething();
if(!$empties.length){
// process submit
}else{
// prevent submit
}
你仍然可以使用jQuery的VAL()函數
var required_inputs = [];
$('input.required').each(function() {
var $this = $(this);
if ($this.val() == "") {
required_inputs.push($this);
}
})
你有哪些是空所需的輸入元素的數組的方式。例如,你可以執行該功能。對每個這樣的輸入進行模糊處理,然後使用這些元素進行處理。
首先,抓住每一個輸入與required
屬性,然後尋找輸入沒有價值。
$('input[required=""]').each(function(){
if (!$(this).val()) {
console.log(this);
//logic
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input required>
<input required>
<input required value='x'>
<input value='y'>
您可以使用filter()
把所有的投入與val()
空,在return語句檢查每個人的價值。
$("#getInputs").click(function() {
var arr = $('input').filter(function() {
return ($(this).val() == '');
});
console.log(arr)
});
input {
display: block;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<button id="getInputs">Get</button>
您可以選擇這樣的,
HTML
<input class="required" />
<input class="required" />
<input class="required" value='x'>
<input value='y'>
JS
$("input:not([value]).required, input[value=''].required")
謝謝
不考慮用戶輸入 – charlietfl
'val()'永遠不會返回'null' – charlietfl
我的意思是在字面意義上是空的。 –
罰款...但這不是'空' – charlietfl