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
Solution 1:
One way is to set all empty fields to disabled before submit, e.g.
functiondisableEmptyInputs(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:
<formonsubmit="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);
};
Solution 2:
This is what I have on a site for exactly this:
$("#my-form").submit(function() {
$(this).find(":input").filter(function () {
return !this.value;
}).attr("disabled", true);
returntrue;
});
It will disable all input fields in your form that doesn't have any value, which makes them not being sent in the request.
Solution 3:
This is what I did using JQuery:
$("#myform").submit(function (event) {
event.preventDefault();
var dataArr = {};
$.each($("form > input[name]"), function (key, value) {
if ($(this).val() != "") {
dataArr[$(this).attr('name')] = $(this).val();
}
});
$.post($(this).attr('action'), dataArr);
alert("Form submitted!");
});
What the above code does:
- Stops the default form submission
- Finds all the input fields that have a data
- Builds an array of the valid data
- Submits the form to the page defined by the action attribute of the form via the POST method
- Displays a message of the form submission.
Solution 4:
Here is a solution using JQuery
HTML
<form id="myForm">
<input name="1"type="text" / >
<input name="2"type="text" / >
<input name="3"type="text" / >
<input name="4"type="text" / >
<button id="sub">Submit</button>
</form>
JS
(function(){
$('#sub').click(function(e){
e.preventDefault();
var data = $('form input').filter(function(index,ele){
return $(ele).val()!= '';
}).serialize();
console.log(data)
})
})()
Post a Comment for "How To Not Pass Empty Input Fields In Html Form"