AnttiM
AnttiM

Reputation: 13

How to not pass empty number input fields in HTML form

I'm currently using code like this, that I found from here, that prevents empty fields from submitting. The forms class is remove-empty-field.

$(document).ready(function() {
$('.remove-empty-fields').submit(function() {
$(this).find(':input').filter(function()
{ return !this.value; }).attr('disabled', 'disabled');
return true; // make sure that the form is still submitted
});
});

I would like to change it so only empty number fields don't get submitted but empty text fields do. It would make submitted email more standard looking.

Upvotes: 1

Views: 233

Answers (1)

Eran Shabi
Eran Shabi

Reputation: 14979

Input fields values are strings, so your option is to know which input is which type and treat them differently. You can do this by the ID of the input, for example.

Another option is to put type="number" on your number inputs and treat them differently because of that, so for each empty input[type="number"], don't submit anything, but for the rest do. So your filter function would look like this:

return !this.value && this.type === "number"

Upvotes: 1

Related Questions