-1

I've noticed form elements also include a name parameter in HTML, as such:

<input type="button" id="btnID" name="btnNAME" value="click me">

I dont really understand the use of name. In the following code snippet, I just change the color of btn to red, via its id. What is the purpose of name attribute? (an example would be nice)

#btnID {
  background-color: red;
}
<input type="button" id="btnID" name="btnNAME" value="click me">
K Split X
  • 2,181
  • 3
  • 11
  • 35

3 Answers3

3

the name attribute isn't really necessary when you are not sending data through it. The id of the form input element can fulfill the purpose of hooking the element with JavaScript and CSS.

The name attribute is used in the HTTP request sent by your browser to the server as a variable name associated with the data contained in the value attribute.

Here I'm taking example of extracting data with php in a login form. If you don't know php you wouldn't probably know $_POST and $_GET. For now just know that they are used to extract data sent with this HTTP request.

<form action="login.php">
    <input type="text" name="user" value="kittyCat">
    <input type="password" name="password" value="querty123">
</form>

Now in login.php file you can extract the data like this:

$userName = $_POST['user'];
$password = $_POST['password'];

here user points to the fist input so $username will be equal to the value of that input, which is "kittyCat". similarly $password will be equal to "qwerty123".

ab29007
  • 7,170
  • 2
  • 14
  • 42
0

Use name attributes for form controls (such as input and select'), as that's the identifier used in the POST or GET call that happens on form submission.

Arun
  • 1,498
  • 1
  • 12
  • 16
-1

The NAME attribute is used for grabbing a value of an element via PHP, e.g.:

HTML w/ PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST'):
    $fn = $_POST['first_name'];
    echo $fn; // prints "Santa" on the page

    //or we can create something:

    ?><p><?php echo $fn; ?></p><?php // creates a p element w/ santa inside

endif;
?>

<form method="post">
<input type="text" name="first_name" value="Santa" />
<input type="submit" value="Do Something" />
</form>

Once the HTML form is submitted, the little block of php code will run.

Just so you know, you can style an element using CSS by grabbing an element by name, e.g.:

HTML

<input name="something" type="text" />

CSS

input[name="something"] { color: red; }
Rommel
  • 3
  • 5