如何不以HTML形式传递空的输入字段 [英] How to not pass empty input fields in HTML form

查看:34
本文介绍了如何不以HTML形式传递空的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中包含每个公司产品的大约100个输入/文本字段.该表格将在一天结束时填写售出的每种产品的编号.

I have a form that has about a hundred input/text fields for each of our companies products. The form is to be filled out at the end of the day with the number of each product that was sold.

如何让表单仅传递相对较小的非空字段子集?

How do I have the form only pass on the relatively small subset of fields that are NOT empty?

我不是在寻找表单验证.用户可以在任何输入字段中输入或不输入值.但是我只希望将输入值的输入字段包含在表单通过的POST中.

I'm not looking for form validation. It's ok for the user to either enter or not enter a value in any of the input fields; however I only want the input fields that did have a value entered into them to be included in the POST that the form passes along.

谢谢

推荐答案

一种方法是将所有空字段设置为在提交前禁用,例如

One way is to set all empty fields to disabled before submit, e.g.

function disableEmptyInputs(form) {
  var controls = form.elements;
  for (var i=0, iLen=controls.length; i<iLen; i++) {
    controls[i].disabled = controls[i].value == '';
  }
}

并在表单的提交侦听器上运行它:

And run it on the form's submit listener:

<form onsubmit="disableEmptyInputs(this)" ...>

因此,任何具有"(空字符串)值的输入都将其 disabled 属性设置为 true ,并且不会提交.

So any input that has a value of "" (empty string) will have its disabled property set to true and it won't be submitted.

或动态添加侦听器:

window.onload = function() {
  document.getElementById('formID').addEventListener('submit', function() {
    Array.prototype.forEach.call(this.elements, function(el) {
      el.disabled = el.value == '';
    });
  }, false);
};

这篇关于如何不以HTML形式传递空的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆