我想检查是否至少已填写/检查/选择了表单的一项。表单使用输入字段、复选框和单选按钮。至少应选择/填写/检查其中一项才能继续填写表格。
我的解决方案如下:
$('#subform').submit(function(e){
els = $('.filter_ext[type="text"], .filter_ext[type="radio"]:checked, .filter_ext[type="checkbox"], select.filter_ext');
empty_count = 0;
els.each(function(){
th = $(this);
cur_val = th.val();
if(cur_val=='' || !th.checked) {
th.prop('disabled', true); // omit empty items from url get variables (nicer url)
empty_count ++;
}
});
if(empty_count == els.length) { // if all are empty stop form submit
e.preventDefault();
} // else proceed with submitting form
});
有更优雅的方法来解决这个问题吗?
编辑 感谢Louys Patrice Bessette的答案,我用以下代码进行了简化(将禁用功能添加到他的解决方案中):
var serialized_orig = $('#subform').serialize();
$('#subform').submit(function(e){
th = $(this);
serialized = th.serialize();
$.each(serialized.split('&'),function(i,v){
item = v.split('=');
item_name = item[0];
item_value = item[1];
if(item_value == '') {
$('.filter_ext[name="'+item_name+'"]').prop('disabled', true);
}
});
if(serialized == serialized_orig) {
e.preventDefault();
}
});
最佳答案
您可以使用 Array.some() 来检测集合中至少有一个元素包含该条件。我为您编写了一个普通的 JS 示例 - 请随意评估它:https://codepen.io/zvona/pen/ywoJxg
它在 jQuery 中看起来像这样(未测试):
const isValid = $('.formElem').some(($elem) => $elem.val().length || $elem.attr('checked'));
关于javascript - 检查表单是否至少有一个已填充/选中/选定的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55092626/