Reputation: 15091
I'm practicing form validation with JavaScript but when I try to retrieve the data from the page it submits to I can't get it.
form.html
<body>
Hello.<br />
<form onsubmit="return validate()" action="process.php" method="POST">
Enter name: <input type="text" id="name" /><br />
Enter phone number: <input type="text" id="number" /><br />
Enter password: <input type="password" id="paswd" /><br />
Is there anything else you would like to add: <input type="text" id="anything" /><br />
<input type="submit" value="Check Form" />
</form>
</body>
process.php
<?php
echo 'Here: '.$_POST['number']
?>
Whatever index I use I get " Undefined index: line 2". What am I doing wrong?
EDIT: So I can't use the id
attribute I need the name
? Is there anyway to prevent coding redundancy since the value of all name
s will be the same as the corresponding id
?
Upvotes: 1
Views: 2653
Reputation: 904
So like Vitor Braga said your inputs need the name of the element, but you only need this if you are using PHP to hadle the values of form in the submit, if you are using javascript to validaate like you said your were praticing you can obtain the value like this:
document.getElementById("number").value
Upvotes: 2
Reputation: 5802
You need to give your form elements names.
<input type="password" id="paswd" name="paswd" />
Interestingly names and ids share the same namespace. If you don't really need the ids, leave them be. Inside a validate function you can always access all elements with the elements
object of the form.
// called onsubmit
var validate = function(e) {
if (this.elements["paswd"].value.length < 4) {
alert("password needs to have at least 4 characters");
return false;
}
return true
};
I usually append the input type to my ids to differentiate them from field names
<label for="paswd-txt">Password: </label>
<input type="text" name="paswd" id="paswd-txt" />
<label for="save-cb">Remember me: </label>
<input type="checkbox" name="save" id="save-cb" value="1"/>
Upvotes: 2
Reputation: 9833
You need name
attribute in your fields
<input type="text" id="number" name="number" />
$_POST
looks for the name
attribute in the field to capture the field values and not id
Upvotes: 7
Reputation: 2212
Your inputs need the name of the element.
Such as:
<input type="text" id="number" name="number" />
The Php gets the form data looking these names, not the ids.
Upvotes: 4
Reputation: 15338
you forgot name
of input:
<input type="text" id="number" name="number" />
Upvotes: 2