'Why does <input> sometimes include "id" and "name" & sometimes neither but producing the same visual output?
Method 1, ex. 1:
<form>
<label for="name"> Name: </label>
<input type="text" id="name" />
</form>
Method 1, ex. 2:
<form>
<label for="name">First name:</label>
<input id="lfname" name="fname" type="text">
</form>
—> Both structures look the same in browser. Both inputs include input id and + input type (in different chronological order, I guess that does not matter when using attributes?) - but: why does the 2nd also include name= again, if it looks the same on the browser anyway?
Method 2, ex. 1:
<form>
<label>
Name:
<input type="text" />
</label>
</form>
Method 2, ex. 2:
<form>
<label>Name
<input id="User" name="Name" type="text" />
</label>
</form>
—> Both structures look the same in browser. Here: In the 2nd, input id and name is used & in the 1st example both are left out and only type specified. How come?
Solution 1:[1]
The attribute name is used for many purposes in PHP it is used to get the data of the input tag and many more.
The attribute id is also used for many purposes like in javascript you get the by using document.getElementById and many more
Solution 2:[2]
name in an input element is used for backend purposes and ID too but in most cases you as a frontend dev will find yourself using it in CSS and JAVASCRIPT as well.
Solution 3:[3]
name is used for form submission in the DOM (Document Object Model).
ID is used for a unique name of HTML controls in the DOM, especially for JavaScript and CSS.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ghulam Mustafa |
| Solution 2 | Nikhil |
| Solution 3 | Vihan Gammanpila |
