HTML Forms
HTML Forms
An HTML form is used to collect user input. The entered data is usually sent to a server for processing.
The <form> Element
The <form> element defines a form and acts as a container for form controls such as text fields, checkboxes, radio buttons, and submit buttons.
<form> form elements go here </form>
The <input> Element
The <input> element is the most commonly used form element. Its behavior depends on the value of the type attribute.
text– single-line text inputradio– select one optioncheckbox– select multiple optionssubmit– submit the formbutton– clickable button
Text Fields
Text fields allow users to enter a single line of text using <input type="text">.
<form> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname"> </form>
The <label> Element
The <label> element defines a label for an input element and improves accessibility and usability.
The for attribute must match the id of the related input element.
Radio Buttons
Radio buttons allow the user to select only one option from a group. All radio buttons in the same group must share the same name value.
<form> <input type="radio" id="html" name="fav_language" value="HTML"> <label for="html">HTML</label><br> <input type="radio" id="css" name="fav_language" value="CSS"> <label for="css">CSS</label><br> <input type="radio" id="js" name="fav_language" value="JavaScript"> <label for="js">JavaScript</label> </form>
Checkboxes
Checkboxes allow users to select zero or more options independently.
<form> <input type="checkbox" id="bike" name="vehicle1" value="Bike"> <label for="bike">I have a bike</label><br> <input type="checkbox" id="car" name="vehicle2" value="Car"> <label for="car">I have a car</label><br> <input type="checkbox" id="boat" name="vehicle3" value="Boat"> <label for="boat">I have a boat</label> </form>
The Submit Button
The submit button sends form data to the server. The destination is defined using the action attribute.
<form action="/action_page.php"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname" value="John"><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname" value="Doe"><br><br> <input type="submit" value="Submit"> </form>
The name Attribute
The name attribute is required for an input field to be included in form submission.
If an input does not have a name, its value will not be sent to the server.
<form action="/action_page.php"> <label for="fname">First name:</label><br> <input type="text" id="fname" value="John"><br><br> <input type="submit" value="Submit"> </form>