View video tutorial

HTML for Attribute

HTML

The HTML for attribute is used to associate a <label> element or an <output> element to a specific element on a form.

Definition and Usage


➔ When a user clicks on the text of a <label>, the associated input is automatically focused.

➔ The <output> element declares an explicit relationship between the result of a calculation and the elements id used to extract that result. This specifies that the ids inside the form are part of the calculation.

Syntax
//In HTML
<!-- Example for input element -->
<label id="nameLabel" for="name">Name:</label>
<input type="text" id="name" name="name">

<!-- Example for output element -->
<form>
    <input type="number" id="a" value="10"> +
    <input type="number" id="b" value="20"> =
    <output name="x" for="a b"></output><br><br>
    <button type="button" onclick="m1(a,b,x)">click</button>
</form>

//In JavaScript
const labelElement = document.getElementById("nameLabel");
labelElement.setAttribute("for", "username");
labelElement.htmlFor = "username";

Applies to

This attribute can be used on the following element.

Attribute Element
for <label> <output>

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML for attribute example</title>
    <style>
        input {
            width: 80px;
            height: 40px;
            text-align: center;
            align-content: center;
        }
        output {
            padding: 13px 40px;
            margin: 10px;
            border: 1px solid #999999;
        }
    </style>
</head>
<body>
    <h3>HTML for attribute example</h3>
    <p>The for attribute is used to associate a label element or an output element with another specific element on the
        form.</p>
    <form oninput="m1(a,b,x)">
        <input type="number" id="a" value="10"> +
        <input type="number" id="b" value="20"> =
        <output name="x" for="a b"></output>
    </form>
    <script>
        function m1(a, b, x) {
            x.value = parseInt(a.value) + parseInt(b.value);
        }
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.