user3553682
user3553682

Reputation:

Is "name" attribute mandatory in <input>, <textarea> and <button> elements?

Is "name" attribute mandatory in <input>, <textarea> and <button> elements? Or maybe we can use id or class instead?

Upvotes: 4

Views: 2980

Answers (4)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

Name is not a required attribute. A small quote from the HTML spec:

The name content attribute gives the name of the form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must not be the empty string.

Notice the "if" in the quote, indicating that it is not required, from a standards perspective.

However, if the input is used with the browsers standard form submission, you won't be able to retrieve the value of the input on the server-side, if you don't have a name to refer to.

If you only need to retrieve the value on the client using JavaScript, then you can use an id, a class, or any other means to select the given input - in that case you can leave the name out if desired.

Upvotes: 3

user3774630
user3774630

Reputation: 266

No its not, but generally you would want it.

Try this

<?php
foreach($_GET AS $key=>$val)
{
    echo "name '$key'  has value '$val'<br>";
}
?>
<form>
<input type="text" name="abc">
<input type="text" id="a">
<input type="text" class="b">
<input type="text">
<input type="submit">
</form>

Upvotes: -1

Andy Holmes
Andy Holmes

Reputation: 8077

name is what gets sent to php scripts for processing so for example $_POST['Telephone'] when used as <input name="Telephone" type="text">. Not required unless being used for processing really.

Upvotes: 1

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2013

  • If these tags are inside a form tag and you are subbmitting that form to a server, then name is required,
  • If you are just using them for client-side purposes and don't want to send them to server, then it is optional.

Upvotes: 6

Related Questions