Just like Caique commented , you can, with JavaScript, add the disabled
property the moment you the form is submitted, so the browser will not include the blank fields:
const form = document.getElementById("form");
form.addEventListener("submit", function(event) {
for (let input of this.elements) {
if (!input.value) {
input.setAttribute("disabled", true);
}
}
});
The same thing happens if you set the name
property to null:
form.addEventListener("submit", function(event) {
for (let input of this.elements) {
if (!input.value) {
input.setAttribute("name", "");
}
}
});
Code Comments
With document.getElementById
we can get the JS reference of the form in the DOM, that is, form
will be the form we want to work on - realize that we need to define the id
attribute in it. Then, using addEventListener
, we add a function that will always be executed when the submit
event of the form is triggered, that is, when the form is submitted - in fact the submit
event is executed immediately before the actual submission of the form browser. In this function, we then traverse all the elements (fields) of the form in question through a% loop of% loop, iterating over for
. The this.elements
, in this case, refers to the object this
. Thus, form
will be the reference to each field of the form, then we check if its input
value is valid and, when it is not, we define the input.value
property as true of it. A field with the disabled
property set is ignored by the browser when the form is submitted, so the blank fields are not sent.