EniunEniunEniunEniun
  • Inicio
  • Blog
  • Cursos
  • Contactar
  • DTD
✕
            Sin resultados Ver todos los resultados

            HTML Form tags

            • Inicio
            • HTML HTML Inglés
            • HTML Form tags
            21/06/2023
            HTML

            HTML

            4. HTML Form tags

            To create an HTML form, use the <form> tag as the container. Inside the form, you can add various input elements to collect user data. Here’s an example of a basic form structure:

            Contenidos del artículo

            Toggle
            • 4. HTML Form tags
            • 4.1. <form> attributes
            • 4.2. Form tags
              • 4.2.1. <fieldset> and <legend> tags
              • 4.2.2. <label> tag
              • 4.2.4. <input> tag
              • 4.2.4. <button> tag
              • 4.2.5. <select> tag
              • 4.2.6. <datalist> tag
              • 4.2.7. <textarea> tag
            • 4.3. Form input attributes
            • 4.4. Form input: type attribute values
            • 4.5. Pattern attribute and regular expressions
            <form action="/submit" method="POST">
              <label for="name">Name:</label>
              <input type="text" id="name" required>
            
              <label for="email">Email:</label>
              <input type="email" id="email" required>
            
              <input type="submit" value="Submit">
            </form>

            In this example, the form has an action attribute specifying where the form data should be submitted. The method attribute determines the HTTP method to be used (POST in this case). Each input element has a type, id, and name attribute for identification and data collection. The submit input triggers form submission.

            4.1. <form> attributes

            • action: It specifies the URL or route to which the form data will be sent when it is submitted.It can be a relative or absolute URL that indicates where the form data will be sent for processing.
            • method: It can be either «GET» or «POST» and determines the HTTP method that will be used to send the form data to the server. The main difference lies in how the data is transmitted.
              • GET: The form data is appended to the URL as query parameters. It is the default method if the method attribute is not specified. It is useful when you want the form data to be visible in the URL, for example, when performing searches.
              • POST: The form data is sent in the body of the HTTP request in a more secure manner and is not shown in the URL. It is suitable for sending sensitive data such as passwords or personal information.

            Both the action and method attributes are used together to determine how the form data will be sent and processed. It is important to consider security and the purpose of the form when choosing the appropriate method. Example:

              <form action="/process-form" method="POST">
                <!-- Form fields -->
              </form>

            4.2. Form tags

            HTML form tags are used to create interactive forms on web pages. Here are some commonly used form tags:

            ElementDescription
            <form>It is used to create a form for user input.
            <fieldset>It is used to group elements in a form. It draws a box around the elements.
            <legend>It is used to define a caption for the <fieldset> element.
            <label>It defines a label for several elements: <input> <meter> <progress> <select> <textarea>
            <input>It is used to specify an input field where the user can enter information.
            <button>It specifies a button.
            <option>It defines an option in a select list. It goes inside a <select>, <optgroup>, or <datalist> element.
            <select>It is used to create a drop-down list.
            <optgroup>It is used to group related options in a <select> element (drop-down list).
            <datalist>It is used to specify a list of pre-defined options for an <input> element.
            <textarea>It defines a multi-line text input control. It is useful to collect user inputs like comments or reviews.
            Table 4.1. Form tags

            Example

            <form>
                <fieldset>
                    <legend>Datos personales</legend>
                    <label>Nombre y apellidos: </label>
                    <input name='nombre' type='text'/><br>
            
                    <label>Sexo: </label>
                    <select>
                        <!--Etiqueta option-->
                        <option value="value1">Hombre</option> 
                        <option value="value2" selected>Mujer</option>
                    </select><br><br>
            
                    <label>Edad: </label>
                    <input type='checkbox' value='20-39' /> 20-39
                    <input type='checkbox' value='40-59' /> 40-59
                    <input type='checkbox' value='60-79' /> 60-79<br><br>
            
                    <label>Email: </label>
                    <input type='email'/><br><br>
            
                    <label>Estudios: </label>
                    <select id="estudios">
                       <optgroup label="Estudios Universitarios">
                          <option>Doctorado</option>
                          <option>Máster</option>
                          <option>Grado</option>
                       </optgroup>
                       <optgroup label="Ciclo Formativo">
                          <option>Grado Superior</option>
                          <option>Grado Medio</option>
                       </optgroup>
                    </select><br><br>
            
                    <label>Elige tu navegador favorito: </label>
                    <input list="browsers">
                    <datalist id="browsers">
                        <option value="Chrome">
                        <option value="Firefox">
                        <option value="Internet Explorer">
                        <option value="Opera">
                        <option value="Safari">
                        <option value="Microsoft Edge">
                    </datalist><br><br>
            
                    <label>Escribe tu mensaje: </label>
                    <textarea rows="10" cols="50"></textarea>
                </fieldset>  
                <input type="submit" value="Enviar" />
            </form>

            CodePen example

            4.2.1. <fieldset> and <legend> tags

            The <fieldset> and <legend> tags in HTML are used to group related form elements together and provide a descriptive caption or title for the group.

            The <fieldset> tag acts as a container that holds a group of form elements. It helps in organizing and structuring the form by visually grouping related fields. Here’s an example:

            <fieldset>
              <legend>Contact Information</legend>
              <label for="name">Name:</label>
              <input type="text" id="name"><br>
              <label for="email">Email:</label>
              <input type="email" id="email"><br>
              <label for="message">Message:</label>
              <textarea id="message"></textarea>
            </fieldset>

            In this example, the <fieldset> tag wraps the group of form elements related to contact information. The <legend> tag is used as a caption or title for the fieldset, providing a description of the group.

            The rendered output will display the legend text as the title of the fieldset, visually separating the grouped fields from other form elements.

            Using <fieldset> and <legend> tags helps improve the accessibility and usability of forms by providing a clear structure and visual grouping of related fields. It also enhances the overall styling and organization of the form.

            4.2.2. <label> tag

            The <label> tag in HTML is used to define a label for an HTML form element. It helps in associating a text description with a form input, making it more accessible and user-friendly. Here’s an example:

            <label for="username">Username:</label>
            <input type="text" id="username">

            In this example, the <label> tag is used to create a label for the username input field. The for attribute of the <label> tag specifies which input element it is associated with. In this case, the for attribute value matches the id attribute of the input field.

            When a user clicks on the label, the corresponding input field is focused or activated. This improves usability and accessibility, as users can click on the label text instead of directly clicking on the input field.

            This allows users to click anywhere within the label text to activate the associated input field.

            Using the <label> tag is important for creating accessible and well-structured forms in HTML. It improves usability, especially for users with assistive technologies.

            4.2.4. <input> tag

            The <input> tag in HTML is a fundamental element used to create various types of form controls that allow users to input data on a web page. It’s one of the most versatile and widely used form elements in HTML. Here’s an overview of how the <input> tag works and some of its common attributes:

            <input type="text" name="username" id="username" value="JohnDoe" />

            In this example, we’re using the <input> tag to create a text input field. Let’s break down the attributes:

            • type: This attribute specifies the type of input control to display. In this case, it’s set to «text,» which creates a single-line text input field. Other common type values include «password,» «email,» «number,» «checkbox,» «radio,» and more, each used to create different types of input controls.
            • name: This attribute assigns a name to the input field, which is used to identify the field when the form is submitted. It’s important for server-side processing.
            • id: The id attribute provides a unique identifier for the input element. It’s useful for JavaScript and CSS when targeting this specific input field.
            • value: The value attribute sets the initial or default value for the input field. In this example, the default text in the input field is «JohnDoe.»

            The <input> tag can be customized with various attributes depending on the desired functionality. For example, for radio buttons and checkboxes, you might use the checked attribute to pre-select an option. For text fields, you can set the placeholder attribute to provide a hint to the user.

            Here are some common <input> types and their purposes:

            • <input type="text">: Single-line text input.
            • <input type="password">: Password input (text is masked).
            • <input type="email">: Email input with email validation.
            • <input type="number">: Numeric input (for numbers).
            • <input type="checkbox">: Checkbox for binary choices.
            • <input type="radio">: Radio button for selecting one option from multiple choices.

            These are just a few examples of the many input types and attributes available with the <input> tag. They play a crucial role in creating interactive and user-friendly forms on websites.

            4.2.4. <button> tag

            The <button> tag in HTML is used to create a clickable button on a webpage. It can be used to trigger a specific action or behavior when clicked. Here’s an example:

            <button>Click me</button>

            In this example, a simple button with the text «Click me» is created. You can customize the appearance and behavior of the button using CSS and JavaScript.

            You can also use the type attribute to define the type of button. Some common values for the type attribute are:

            • submit: A button that submits a form.
            • reset: A button that resets form inputs to their initial values.
            <button type="submit">Submit</button>

            This button, when clicked, will submit the form it belongs to.

            You can further enhance the functionality of the button by adding event listeners in JavaScript to perform specific actions when it is clicked.

            4.2.5. <select> tag

            The <select> element in HTML is used to create a dropdown list or a selection menu. It allows users to choose one or multiple options from a list of predefined values. Here’s an example of how to use the <select> element:

            <select>
              <option value="option1">Option 1</option>
              <option value="option2" selected>Option 2</option>
              <option value="option3">Option 3</option>
            </select>

            In this example, we have a <select> element with three <option> elements inside it. Each <option> represents a selectable item in the dropdown list. The value attribute specifies the value associated with each option, which can be used for form submission or JavaScript manipulation. Furthermore, the second <option> element has the selected attribute, which means «Option 2» will be pre-selected when the page loads. Users can still change the selection if desired.

            You can also add the multiple attribute to allow multiple selections:

            <select multiple>
              <option value="option1">Option 1</option>
              <option value="option2">Option 2</option>
              <option value="option3">Option 3</option>
            </select>

            The <optgroup> tag is used within a <select> element to group several related options into a category or set. This provides visual organization to the options within the dropdown list. The <optgroup> tag must contain one or more <option> tags that represent the options within that group.

            <select>
              <optgroup label="Fruits">
                <option value="apple">Apple</option>
                <option value="orange">Orange</option>
                <option value="banana">Banana</option>
              </optgroup>
              <optgroup label="Vegetables">
                <option value="carrot">Carrot</option>
                <option value="broccoli">Broccoli</option>
                <option value="spinach">Spinach</option>
              </optgroup>
            </select>

            In this example, we have created a dropdown list with two groups: «Fruits» and «Vegetables.» Each group is defined by the <optgroup> tag, which has a label attribute specifying the group’s name. Within each group, we have included <option> tags representing individual options like «Apple,» «Orange,» «Carrot,» etc.

            When rendered in a web browser, this will create a dropdown list with options visually grouped under the group labels. This makes it easier for users to find and select the options they want in an organized manner.

            4.2.6. <datalist> tag

            The <datalist> tag in HTML is used in conjunction with the <input> tag to provide a list of predefined options that assist users in selecting a value as they type into an input field (<input>). This tag creates a dropdown list of suggestions based on the options you define, making data entry easier and enhancing the user experience.

            Here’s an example of how the <datalist> tag is used:

            <label for="fruits">Select a fruit:</label>
            <input list="fruits" id="fruit" name="fruit" />
            
            <datalist id="fruits">
              <option value="Apple"></option>
              <option value="Banana"></option>
              <option value="Orange"></option>
              <option value="Grape"></option>
              <option value="Pear"></option>
            </datalist>

            In this example, we’ve created a text input field using the <input> tag and assigned it a list attribute that corresponds to the id of the <datalist> tag. The <datalist> contains options (<option>) that represent the available suggestions for the input field.

            When a user starts typing in the input field, they will see a dropdown list with the options from the <datalist>. They can either select one of the options or continue typing. This is particularly useful for forms where users need to choose an option from a predefined list, such as a list of countries or products.

            The use of <datalist> enhances usability and makes data entry easier for users, especially on mobile devices and touch screens.

            4.2.7. <textarea> tag

            <textarea> is an HTML tag used to create a multi-line text input area. It supports two attributes, rows and cols, which define the visible number of rows and columns respectively.

            • The rows attribute specifies the visible height of the textarea in terms of rows. It determines the number of lines visible without scrolling.
            • The cols attribute specifies the visible width of the textarea in terms of columns. It determines the number of characters visible horizontally without scrolling.

            Here’s an example of how to use the rows and cols attributes in a <textarea> tag:

            <textarea rows="4" cols="40">
            This is a textarea with 4 rows and 40 columns.
            </textarea>

            In this example, the textarea will be displayed with 4 visible rows and 40 visible columns. The text inside the <textarea> will be shown within this specified size.

            4.3. Form input attributes

            Form input attributes are used to specify additional properties or behaviors of HTML input elements within a form. Here are some commonly used form input attributes:

            AttributeDescription
            type Specifies the type of input control, such as text, password, checkbox, radio, etc.
            valueInitial value for an input field.
            readonlyThe input field is read-only.
            disabledThe input field is unusable and unclickable.
            sizeVisible width, in characters, of an input field. The default value for size is 20. It works with these input types: text, search, tel, url, email, and password.
            maxlength It specifies the maximum number of characters allowed in an input field.
            min / maxIt specifies the minimum and maximum values for an input field.
            patternIt allows you to apply regular expressions to validate and control the input values of certain elements. It works with the following input types: text, date, search, url, tel, email, and password.
            placeholder It describes the expected value of an input field. It works with the following input types: text, search, url, tel, email, and password.
            requiredIt specifies that an input field must be filled out.
            autofocus It specifies that an input field should automatically get focus when the page loads.
            Table 4.2. Form input attributes

            Example

            <form>
              <label for="name">Name:</label>
              <input type="text" id="name" name="name" placeholder="Enter your name" required>
              
              <label for="email">Email:</label>
              <input type="email" id="email" name="email" placeholder="Enter your email" required>
              
              <label for="password">Password:</label>
              <input type="password" id="password" name="password" minlength="8" maxlength="16" required>
              
              <label for="age">Age:</label>
              <input type="number" id="age" name="age" min="18" max="99" required>
              
              <label for="terms">I agree to the terms and conditions:</label>
              <input type="checkbox" id="terms" name="terms" required>
              
              <button type="submit">Submit</button>
            </form>

            In this example, we have used various attributes such as type, id, name, placeholder, required, minlength, maxlength, min, and max for the input fields. We have also used the for attribute in the <label> tags to associate them with the corresponding fields.

            4.4. Form input: type attribute values

            The type attribute is used in HTML input elements to define the type of data that can be entered or selected by the user. It helps to determine the appearance and behavior of the input field. Here are some commonly used values for the type attribute:

            TypeDescription
            checkboxCheck box allowing single values to be selected/deselected.
            colorControl for specifying a color; opening a color picker.
            dateControl for entering a date (year, month, and day, with no time). 
            emailField for editing an email address. Looks like a text input, but has validation parameters.
            fileControl that lets the user select a file. Use the accept attribute to define the types of files that the control can select.
            imageGraphical submit button. Displays an image defined by the src attribute. The alt attribute displays if the image src is missing.
            monthControl for entering a month and year..
            numberControl for entering a number. Displays a spinner and adds default validation. 
            passwordSingle-line text field whose value is obscured. 
            radioRadio button, allowing a single value to be selected out of multiple choices with the same name value.
            rangeControl for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle value. Used in conjunction min and max to define the range of acceptable values.
            searchSingle-line text field for entering search strings. 
            submitButton that submits the form.
            telControl for entering a telephone number.
            textDefault value. A single-line text field. 
            timeControl for entering a time value.
            urlField for entering a URL. Looks like a text input, but has validation parameters.
            weekControl for entering a date.
            Table 4.3. Type attribute values

            Example

            <form>
              <label for="check">Acepto condiciones</label>
              <input type="checkbox" id="check"><br>
              <label for="color">Elige un color:</label>
              <input type="color" id="color"><br>
              <label for="fecha">Elige una fecha:</label>
              <input type="date" id="fecha"><br>
              <label for="correo">Indica tu correo:</label>
              <input type="email" id="correo"><br>
              <label for="archivo">Selecciona un archivo:</label>
              <input type="file" id="archivo">   <br>
              <label for="archivo">Pincha en la imagen:</label>                                                         
              <input type="image"  src="https://www.eniun.com/wp-content/uploads/eniun-icon-user-experience.svg" alt="Submit" width="38" height="38"><br>
              <label for="mes">Indica el mes:</label>
              <input type="month" id="mes"><br>
              <label for="numero">Selecciona un número:</label>
              <input type="number" id="numero"><br>
              <label for="contrasenya">Indica tu contraseña:</label>
              <input type="password" id="contrasenya"><br>
              <label for="radio">Esto es un radio button:</label>
              <input type="radio" id="radio"><br>
              <label for="rango">Selecciona un número del rango:</label>
              <input type="range" id="rango" min="0" max="100"><br>
              <label for="buscar">Campo de búsqueda:</label>
              <input type="search" id="buscar"><input type="submit" value="Enviar"><br>
              <label for="telefono">Indica tu teléfono:</label>
              <input type="tel" id="telefono"><br>
              <label for="nombre">Indica tu nombre:</label>
              <input type="text" id="nombre"><br>
              <label for="hora">Indica la hora:</label>
              <input type="time" id="hora"><br>
              <label for="url">Indica una URL:</label>
              <input type="url" id="url"><br>
              <label for="semana">Indica la semana:</label>
              <input type="week"><br>
              <input type="button" value="Enviar">
             </form>

            CodePen example

            4.5. Pattern attribute and regular expressions

            The pattern attribute allows you to apply regular expressions to validate and control the input values of certain elements. Regular expressions are powerful patterns used for matching and manipulating strings. 

            A regular expression, often abbreviated as regex or regexp, is a sequence of characters that forms a search pattern. It is a powerful tool used for pattern matching and manipulating strings.

            Here are some commonly used regular expressions in HTML attributes:

            ExpressionDescription
            [abc]Any of the characters between the brackets
            [^abc]Any character NOT between the brackets
            [a-g]Any of the characters between the brackets
            (a|b)Any of the alternatives separated with |
            MetacharacterDescription
            .A single character, except newline or line terminator
            \w\ d \sWord, digit, whitespace character
            \W \D \SNon-word character, non-digit character, non-whitespace character
            \t \n \rTab character, new line character, carriage return character
            QuantifierDescription
            a* a+ a?Zero or more, one or more, zero or one occurrences
            a{5} a{2,}Only 5, 2 or more
            a{1,3}Between 1 and 3
            ^aAny string with a at the beginning of it
            a$Any string with a at the end of it
            Table 4.4. Pattern attribute and regular expressions

            For a complete reference, go to Complete JavaScript RegExp Reference.

            Example

            Here are some commonly used regular expressions in HTML attributes:

            • Numeric Input: This pattern allows only numeric input in the field.

            <input type="number" pattern="[0-9]+">

            • Custom Pattern: This pattern specifies a custom format where the input should start with three letters followed by three digits.

            <input type="text" pattern="[A-Za-z]{3}\d{3}">

            • ZIP Code Validation: This pattern ensures that the input value is a valid 5-digit ZIP code.

            <input type="text" pattern="[0-9]{5}">

            • Date Validation (YYYY-MM-DD format): This pattern validates the input value as a date in the format of YYYY-MM-DD.

            <input type="text" pattern="\d{4}-\d{2}-\d{2}">

            • Username Validation (alphanumeric characters only): This pattern allows only alphanumeric characters for the username input.

            <input type="text" pattern="[A-Za-z0-9]+">

            RegExr is an online tool that provides a user-friendly interface for working with regular expressions.

            Exercise

            Test

            Navegación de entradas

            ← HTML Content and text tags
            HTML Table tags →

            HTML Tutorial

            • 1. HTML: HyperText Markup Language
            • 2. Semantic tags
            • 3. Content and text tags
            • 4. Form tags
            • 5. Table tags
            • 6. Tags for embedding content
            • 7. Page jumping
            • 8. Metadata or meta tags
            • 9. HTML validation
            • 10. Ordered elements
            • 11. HTML. Technical vocabulary skills
            • 12. HTML factors for SEO
            • 13. Solved exercises
            Ver más cursos

            ☕︎
            ¡Invítanos a un café!

            ¡Invítanos a un café!

            ¿Cómo donar?
            Ayúdanos a seguir creando contenido relacionado con la informática y el diseño y desarrollo web en Eniun. ¡Gracias por tu apoyo!
            Eniun

            info@eniun.com
            Reportar un error

            Servicios

            Desarrollo Web
            Diseño Web
            Marketing Digital
            Social Media
            Experiencia de Usuario
            Cursos formativos

            Suscríbete a la newsletter

            Únete a nuestra comunidad para recibir contenido exclusivo y relevante para diseñadores y desarrolladores web.

            Apuntarme

            © 2026 Eniun | Política de privacidad y cookies

                      Sin resultados Ver todos los resultados