HTML Forms - herougo/SoftwareEngineerKnowledgeRepository GitHub Wiki

Reasons to Use the form Tag

  1. Keyboard and accessibility support

    • Enter key submits the form automatically
    • Screen readers understand form semantics
    • Correct focus handling
  2. Native validation

  3. Automatic data collection (e.g. new FormData(form))

  4. Tooling compatibility (e.g. autofill, browser extensions, analytics, etc)

How to use the form Tag

Examples from Web Dev Simplified: https://www.youtube.com/watch?v=fNcJuPIZ2WE

Note:

  • "for" attribute references the id of an element
  • "for" attribute use cases
    • allows for Screen Reader Compatibility
    • when label is clicked, it brings you to the correct input
  • gender radio buttons all have the same name
  • "name" attribute use cases
    • autocomplete clues
    • to create a name-value pair for the purpose of form submission to a server
    • grouping radio buttons
<body>
	<form>
		<div>
			<label for="form__name">Name</label>
			<input type="text" name="name" id="form__name" required>
		</div>
		<div>
			<label for="password">Name</label>
			<input type="password" name="password" id="password" required>
		</div>
		<div>
			<label for="date">Name</label>
			<input type="date" name="date" id="date" required>
		</div>
		<div>
			Gender
			<div>
				<label for="male">Male</label>
				<input type="radio" name="gender" id="male" required>
			</div>
			<div>
				<label for="female">Female</label>
				<input type="radio" name="gender" id="female" required>
			</div>
		</div>
		<div>
			<label for="file">File</label>
			<input type="file" name="file" id="file">
		</div>
		<input type="hidden" name="hidden" value="hi">
		<div>
			<label for="bio">Bio</label>
			<textarea name="bio" id="bio"></textarea>
		</div>
		<div>
			<label for="eyeColour">Eye Colour</label>
			<select name="eyeColour" id="eyeColour">
				<option value="green">Green</option>
				<option label="Red" value="red"></option>
			</select>
		</div>
		<button type="reset">Reset</button>
		<button type="submit">Submit</button>
	</form>
</body>
⚠️ **GitHub.com Fallback** ⚠️