Is there a way to return a list / array of all the field names that are contained within a form? I.e if i made a form with 10 fields ('name', 'email' etc...) on submit i can determine what the element names are?
8 Answers
JavaScript
The raw JS way to do that is:
const inputs = document['<your form name>'].getElementsByTagName("input");
for (const input in inputs) {
if (inputs[input] && inputs[input].name) {
console.log(inputs[input].name);
}
}
PHP
Yes. They are all in the superglobals $_GET (for all of the GET variables), $_POST (if your form has method="POST"), and $_REQUEST ($_REQUEST is, by default Environment, Get, Post, Cookie, and Server (in that order) you can read more here).
If you want to just get the names, then you can use array_keys on any of the above.
4 Comments
$_REQUEST combines $_GET, $_POST, and $_COOKIE so it's possible for values from the form to be overwritten by values in one of the other two.input tags. Use getElementsByTagName("select"); etc. for the rest.inputs var but then later referenced it with lst var. I edited and fixed. Also I used the code as I could only find other answers using the form's ID (which one doesn't always have). Thanks!In JavaScript we can get the name attribute of each form element like this:
$('form').on('submit', function () {
var names = [];
$.each($(this).find('input, textarea'), function () {
names.push(this.name);
});
});
This gathers the name attribute of each input or textarea element in the form and puts them in an array, names.
Note that .on() is new as of jQuery 1.7 and in this case is the same as using .bind(): http://api.jquery.com/on
In PHP you can loop through each of the $_GET or $_POST variables:
<?php
$names = array();
if (isset($_POST) && !empty($_POST)) {
foreach ($_POST as $key => $val) {
//$key is the name you wanted, and $val is the value of that input
$names[] = $key;
}
}
?>
And again, the $names variable is an array of all the names of form elements.
Update
If you want to create an associative array of names : values in JS you can do this:
$('form').on('submit', function () {
var names = {};
$.each($(this).find('input, textarea'), function () {
names[this.name] = this.value;
});
});
Now you can access the names variable like this:
alert(names.email);//this will alert the value of the input who's name is `email`
8 Comments
names : values then try my update.jQuery serialize: http://api.jquery.com/serialize/
$('form').submit(function() {
alert($(this).serialize());
return false;
});
Comments
:input selector will find form elements in client
http://api.jquery.com/input-selector/
demo http://jsfiddle.net/JBsbL/
$('form').submit(function() {
var inputList = [];
$(this).find(':input').each(function() {
inputList.push(this.name);
})
alert(inputList.join(', '))
return false;
})