Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not pass empty input fields in HTML form

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?

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.

Thanks

like image 382
jasdak Avatar asked Mar 15 '23 10:03

jasdak


1 Answers

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)" ...>

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

Or to add the listener dynamically:

window.onload = function() {
  document.getElementById('formID').addEventListener('submit', function() {
    Array.prototype.forEach.call(this.elements, function(el) {
      el.disabled = el.value == '';
    });
  }, false);
};
like image 167
RobG Avatar answered Mar 25 '23 18:03

RobG