You can iterate the FormData
and check if any field of the form has value. Just iterate the property .entries()
which returns for each field an array with a pair of values, the first being the name
and the second the value
. If a field is empty, the second item of the array is empty.
For example, if the input campo
empty will generate the array:
['campo', ''] // name, value
With a for
you iterate all returned arrays by checking with .includes('')
if any of these arrays have an empty item. The first one you do not find already indicates that the FormaData
loaded form value. Just do a negative check with !
.
See the code below that you will understand:
$("form[name='alpha']").submit(function(e){
e.preventDefault();
let form_data = new FormData($("form[name='alpha']")[0]);
let passou;
for(let par of form_data.entries()){
if(!par.includes('')){
passou = true;
break;
}
}
if(!passou){
console.log("Formulário está vazio. Significa que nenhum campo possui valor.");
return;
}
console.log("Formulário possui algum dado. Significa que pelo menos um campo possui valor.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="alpha">
<input type="text" name="campo"></input>
<input type="text" name="campo2"></input>
<select name="campo3">
<option value="">...</option>
<option value="2">1</option>
</select>
<button>Enviar</button>
</form>
I didn’t really understand what you wanted to do. From the little I understood, you know if any data was sent by the behavior of the backend and/ or the return you expect from AJAX.
– Sam
No... what I need to know is if there’s any kind of
length
orconsole log
to know if the information was loaded into the / formData variable before sending.– WEB Last Wolf