HTML Forms
HTML Forms
HTML Forms are used to collect user input. The <form> element wraps all the form controls and contains attributes that specify how the form behaves.
Form Element
The <form> element has several attributes:
- action - URL where the form data is sent when submitted.
- method - HTTP method used when sending form data (GET or POST).
<form action="submit_form.php" method="post"> </form>
Form Controls
HTML provides several input types to create form controls:
- <input> - Used for various types of user input (text, password, checkbox, etc.).
- <textarea> - A multi-line input field for text.
- <button> - A clickable button.
- <select> - A dropdown list.
- <label> - Defines a label for an input element.
Input Types
The <input> element can take various types:
<form> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <label for="password">Password:</label> <input type="password" id="password" name="password"> <input type="submit" value="Submit"> </form>
Textarea Example
<form> <label for="message">Message:</label> <textarea id="message" name="message">Enter your message here...</textarea> <input type="submit" value="Send"> </form>
Select Dropdown Example
<form> <label for="cars">Choose a car:</label> <select id="cars" name="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> <input type="submit" value="Submit"> </form>
Checkbox and Radio Buttons
Checkboxes allow the user to select one or more options, while radio buttons allow for selecting only one option from a set:
<form> <label><input type="checkbox" name="vehicle1" value="Bike"> I have a bike</label><br> <label><input type="checkbox" name="vehicle2" value="Car"> I have a car</label><br> <label><input type="radio" name="gender" value="male"> Male</label><br> <label><input type="radio" name="gender" value="female"> Female</label><br> <input type="submit" value="Submit"> </form>
Form Validation
HTML5 provides built-in form validation by using attributes such as required, minlength, and maxlength.
<form> <label for="username">Username (min 5 characters):</label> <input type="text" id="username" name="username" required minlength="5"> <input type="submit" value="Submit"> </form>