首页 > 解决方案 > 检查表单是否至少有一个填充/选中/选定元素

问题描述

我想检查是否已填写/选中/选择了至少一个表单项目。表单使用输入字段、复选框和单选按钮。至少应选择/填写/检查其中一项以使表格继续进行。

我的解决方案如下:

$('#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();

  }

});

标签: javascriptjquery

解决方案


您可以Array.some()用于检测集合中的至少一个元素包含该条件。我为您编写了一个香草 JS 示例 - 随时评估它:https ://codepen.io/zvona/pen/ywoJxg

它在 jQuery 中看起来像这样(未经测试):

const isValid = $('.formElem').some(($elem) => $elem.val().length || $elem.attr('checked'));

推荐阅读