2013-06-18 36 views
0

標題使得這看起來很簡單,我試着用google搜索,但我甚至不確定如何說出我正在嘗試做的事情。檢查jQuery中的相同字段是否爲空

我有一組看起來像這樣

<tr> 
    <td><strong>File Label:</strong></td> 
    <td><input type="text" name="label[]" id="label" class="label" /></td> 
    <td><strong>Student File (pdf):</strong></td> 
    <td><input type="file" name="file[]" id="file" class="file" /></td> 
</tr> 
<tr> 
    <td><strong>File Label:</strong></td> 
    <td><input type="text" name="label[]" id="label" class="label" /></td> 
    <td><strong>Student File (pdf):</strong></td> 
    <td><input type="file" name="file[]" id="file" class="file" /></td> 
</tr> 
<tr> 
    <td><strong>File Label:</strong></td> 
    <td><input type="text" name="label[]" id="label" class="label" /></td> 
    <td><strong>Student File (pdf):</strong></td> 
    <td><input type="file" name="file[]" id="file" class="file" /></td> 
</tr> 

正如你看到的,label[]file[]重複字段。

如何使用jQuery,我可以確保在允許表單提交之前至少有1個label和1 file不爲空/空。

我嘗試這一點,但它未能

$('.label').each(function(){ 
    if($(this).val() == '') 
    { 
     alert('Stop Form'); 
    } 
    else 
    { 
     alert('Submit Form'); 
    } 
}); 
+1

您應該始終使用唯一的ID。如果你不這樣做,你的代碼現在可能會工作,但以後可能會造成很多麻煩。 – kajacx

+0

無論如何,該ID將重複,因爲只有1 存在...其餘的獲得通過jquery添加重複字段多次作爲用戶需要。 – ipixel

+2

然後爲'id'添加一個遞增的數字,或者使用'class'名稱。 'id''[***必須在文檔中是唯一的](http://www.w3.org/TR/html401/struct/global.html#h-7.5.2)'(** *重點***我的)。 –

回答

0

你可以使用

$('[name="label[]"]').filter(function(){ return $(this).val() }).length >0 

如果你要檢查一對夫婦名/文件(即在同一TR),那麼你可以做

然後檢查notEmptyTr.length>0

+0

這很好用!我將不得不閱讀.filter()。非常感謝! – ipixel