How to get form values before Submit with jQuery?

Asked

Viewed 1,457 times

0

There are ways, before the form is sent, I can get the values of each form input using jQuery?

  • yes, just treat the event submit, and depending on what you need to do with the values, you can just serialize the form, something like that var valores = $("form").serializeArray()

  • Yes, with .serialize()

  • Cool, so I understood the serialize will bring all the fields I can put in a variable right? Then I use split to separate the value of each field?

  • You want the values separated in an array?

1 answer

2


Using .serializeArray() you will create an array of objects where each object will have two pairs of values:

[{
   "name": "nome do elemento",
   "value": "valor do elemento",
}]

For example, if I have the input:

<input type="text" name="nome" value="Fulano de Tal">

The result would be:

[{
   "name": "nome",
   "value": "Fulano de Tal",
}]

If you want to just take the value of objects and save in another array, just use for...of. Example:

$("form").submit(function(e){
   e.preventDefault();
   var valores = []; // array para guardar os valores
   for(var valor of $(this).serializeArray()){
      valores.push(valor.value);
   }
   console.log(valores);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form> 
   <input type="text" name="nome" value="Fulano de Tal">
   <br>
   <input type="text" name="email" value="[email protected]">
   <br>
   <button>Enviar</button>
</form>

  • show, that’s just what I needed, thank you!

Browser other questions tagged

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