2017-04-21 68 views
0

我想選擇所有輸入(文本框)在我的窗體中有需要的類和沒有價值。所以我使用:使用數值屬性選擇所有輸入

$('input[value=""]', '.required') 

我的問題是,即使用戶輸入在文本框中的值時,VAL()返回值,但價值仍是空的,所以我上面的jQuery還是選擇了所有輸入中的哪以前是空的,它不應該。我如何選擇val爲空的所有輸入?

回答

2

輸入的value attributevalue property在用戶編輯後不相同。

使用filter()並檢查值屬性...喜歡的東西:

var $empties = $('input[required]').filter(function(){ 
    return !this.value; 
}).doSomething(); 

if(!$empties.length){ 
    // process submit 
}else{ 
    // prevent submit 
} 
0

你仍然可以使用jQuery的VAL()函數

var required_inputs = []; 
$('input.required').each(function() { 
    var $this = $(this); 
    if ($this.val() == "") { 
     required_inputs.push($this); 
    } 
}) 

你有哪些是空所需的輸入元素的數組的方式。例如,你可以執行該功能。對每個這樣的輸入進行模糊處理,然後使用這些元素進行處理。

2

首先,抓住每一個輸入與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'>

0

您可以使用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>

+0

'val()'永遠不會返回'null' – charlietfl

+0

我的意思是在字面意義上是空的。 –

+0

罰款...但這不是'空' – charlietfl

-1

您可以選擇這樣的,

HTML

<input class="required" /> 
<input class="required" /> 
<input class="required" value='x'> 
<input value='y'> 

JS

$("input:not([value]).required, input[value=''].required") 

謝謝

+0

不考慮用戶輸入 – charlietfl