2013-04-26 118 views
0

我的頁面中有多個選擇輸入,它們是用相同名稱動態創建的。驗證具有相同名稱jQuery的多個字段?

我的代碼:

<select name="area[]" id="area[]" class="area"> 
    <option value="">Select Area</option> 
    <? 
    $cities = $this->city_model->get_all($posters->product_id); 
     foreach($cities as $city) { ?> 
      <option value="<?=$city->city_id?>"><?=$city->city_name?></option> 
     <? } ?> 
</select> 

我想要的用戶選擇從每個選擇輸入一個值,我使用jQuery的功能是這樣的:

$('.area').each(function(){ 
if($(this).val() == "") { 
    alert("please select Area"); 
} return false; 
}); 

$('.quantity').each(function(){ 
if($(this).val() == "" || $(this).val() == 0) { 
    alert("please select Quantity"); 
    return false; 
} 
}); 
$('#form').submit(); 

我也一樣同它,它是也工作,但它也提交的表格,即使我限制它在

<input type="submit" name="something" id="something" value="something" onclick="checkType();return false;">  
+1

什麼是 「不工作」? – Johan 2013-04-26 14:46:35

+0

JavaScript控制檯中的任何錯誤? – Blazemonger 2013-04-26 14:47:13

回答

3

你是缺少一個關閉大括號在你的陳述上。試試這個:

$('.area').each(function(){ 
    if($(this).val() === "") { 
     alert("please select Area"); 
     return false; 
    } 
}); 

編輯:我重新添加了return false部分,因爲它很可能是OP只希望不管顯示1個警報有多少項目是無效的。

Here is a working example

+2

'==「」'對於'0'是正確的,可能有問題。 – gdoron 2013-04-26 14:49:34

+0

@gdoron:好點,將更新 – musefan 2013-04-26 14:50:35

+0

這是一個很好的幫助! – 2013-04-26 15:02:29

1
$('form').submit(function(){ 
    var unSelected = $('select').filter(function(){ 
     return this.value === ""; 
    }).length > 0; 

    if (unSelected) 
     alert('Error!'); 
}); 
+0

或'var unSelected = $('select')。filter(function(){ return!this.value; })。length;'? – Johan 2013-04-26 14:52:57

+0

@Johan,'!0'評估爲** true **,這在這裏不合適。 – gdoron 2013-04-26 14:54:10

0

試試這個:

<script>$('.area').each(function() { 
     if ($(this).val() == '') { 
      alert("please select Area"); 
      return false; 
     } 
    }); 
</script> 
相關問題