9
Using jQuery I can use the method .serialize()
to return in string form all the form items with their respective values, for example, the form below, will return me:
nome=dvd&email=dvd%40dvd.com&sexo=1
Form:
$("form").on("submit", function(e){
e.preventDefault();
var form = $(this).serialize();
console.log(form);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="nome" value="dvd" />
<br />
<input type="text" name="email" value="[email protected]" />
<br />
<input type="radio" name="sexo" value="1" checked> masculino
<input type="radio" name="sexo" value="2"> feminino
<br />
<input type="submit" value="Enviar" />
</form>
How could I get the same string (result of serialize()
jQuery) but using pure Javascript?
Consider that the form above is just a basic example. The form may have other elements, such as
select
,textarea
,button
etc..
Thanks! It worked smoothly.
– Sam
Take care if your app has to support old browsers. Ref compatibility table here https://developer.mozilla.org/en-US/docs/Web/API/FormData
– nbkhope