2016-05-13 43 views
0

我正在使用聚合物鐵形式的組件,並試圖驗證是否至少有一個複選框中的一個複選框被選中。聚合物鐵形式驗證至少一個複選框被選中

當我調用一個iron-form的submit()時,調用validate函數。我如何添加自定義驗證規則以確保至少有一個複選框被選中?

回答

2

使用querySelectorAll('input[type="checkbox"]:checked').length可以獲得檢查數量checkboxes

如果值爲0,則顯示/警告錯誤消息並阻止提交表單。

var myForm = document.getElementById('myForm'); 
 
myForm.addEventListener("submit", function(e) { 
 
    var no_of_cb_checked = myForm.querySelectorAll('input[type="checkbox"]:checked').length; 
 
    if (no_of_cb_checked == 0) { 
 
    e.preventDefault(); 
 
    alert('Select atleast one checkbox'); 
 
    } 
 
});
<form id='myForm'> 
 
<input type='checkbox' name='form1' value='CB1'>CB1 
 
<input type='checkbox' name='form1' value='CB2'>CB2 
 
<input type='checkbox' name='form1' value='CB3'>CB3 
 
<input type='checkbox' name='form1' value='CB4'>CB4 
 
<input type='submit'> 
 
</form>

相關問題