javascript - 检查表单是否至少有一个已填充/选中/选定的元素

标签 javascript jquery

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

我的解决方案如下:

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

相关文章:

javascript - 在 Bootstrap 模式中验证输入文本

javascript - 我想在我的 cookie 中使用未转义的字符 (jquery)

javascript - 如何使用 .replaceWith() 将函数附加到可拖动项

javascript - 使用 CSS 或 Java 显示或隐藏空白内容区域

javascript - 按行获取单选按钮 - Javascript

javascript - res.locals,req.variable 在 node.js 中返回未定义

javascript - 让 .animate() 和 .data() 一起工作

javascript - 在运行时在 Javascript 、 jQuery 中为图像标签指定新源

javascript - 证明行中图像的对齐方式(ala Google Images)

javascript - 我可以仅使用 Masonry.js 获得 "infinite scroll"效果吗?