How do I find out if the form was loaded into a variable or not?

Asked

Viewed 173 times

-2

Every time I’m messing with forms I usually create a variable to send date by ajax In the future, the problem is that I always curl up to find out if he collected the date or not, and needed some way to figure it out.

My code looks something like this:

//Script JS
let form_data = new FormData($("form[name='alpha']")[0]);
<!-- Jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- HTML -->
<form name="alpha">
  <input type="text" name="campo"></input>
</form>

The question is, how do I know if it is collecting data from the field and not generating an empty 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.

  • No... what I need to know is if there’s any kind of length or console log to know if the information was loaded into the / formData variable before sending.

1 answer

2


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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.