javascript - 检查表单是否至少有一个填充/选中/选定元素
问题描述
我想检查是否已填写/选中/选择了至少一个表单项目。表单使用输入字段、复选框和单选按钮。至少应选择/填写/检查其中一项以使表格继续进行。
我的解决方案如下:
$('#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'));
推荐阅读
- xml - Progress 4GL-将包含 NULL 字符的 Zip 文件从 Memptr 发送到 XML 节点?
- regex - 在 PowerShell 字符串中的 32 个字符 + 空格后返回新行
- java - 为什么我得到-2147483648和-1的乘法,负数,即-2147483648,而不是+2147483648
- ionic-framework - 使用动态离子选择选项将值设置为离子选择框
- php - 如何从较大的整数生成唯一的小整数
- c++ - 如何绘制图形?
- javascript - 无法从两个不同的查询返回操作数据
- jmeter - 如何在 Jmeter 中创建动态 JSON 对象?
- python - 如果输入是整数输入的for循环中的字符串,我如何排除1次尝试
- javascript - 如何在 Chonky.js 中进行选择文件操作