I am using ajax to send data to the server, I have multiple inputs with the same name so I am using the below code to send the data, but I have one issue that is I want to send the input value to the server which does not have empty, null, undefined and zero value in textbox.
for example, if I have 5 inputs with the name as name[] and there are I filled in only 2 input.
when I submit the form then only 2 inputs will send through ajax.
Please help how me achieve the goal.
I am getting this type of array in payload name: ["value1", "value2", " ", " ", " "] but it should be name: ["value1", "value2"] bcz I have input only in two textbox
By definition, form field values are strings, so, you will either get an empty string “” if nothing has been entered in a field or you will get a “0” if a zero has been entered in a field. These are the only two values you need to test for.
Next, you should trim user entered data before validating it. You should also not write out code for every possible value. Use an array instead and test if a value is in the array. This lets you change the operation of the code simply by modifying the entries in the array.
See this example code -
// define what to remove
const remove = ["","0"];
// define a filter() call-back function named 'filter'
function filter(item) {
if (remove.includes(item)) {
return false;
}
return true;
}
Your code would become -
var name = [];
$('input[name="name[]"]').each(function() {
// trim each data item
name.push(this.value.trim());
});
// filter the array of data
name = name.filter(filter);