HTML Input Attributes


HTML provides many attributes to make the process of getting data from the user easier with the help of forms, and enhance the overall user experience. Some important attributes and their uses are explained below.


maxLength Attribute


The maxLength attribute is used to specify the max number of characters that can be used in the input.



<form>
  <label for="pin">Enter PIN: </label>
  <input type="text" maxlength="4" id="pin" />
</form>

Live Demo!


Output:


Pattern Attribute


The input pattern attribute is used to specify regular expressions which becomes the required format for the input. For example for a USA phone number of the format 123-456-7890 following pattern can be used:



<form action="handle_phone.php" method="post">
  <label for="usanum">Enter Phone: </label>
  <input type="text" required pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="usanum" name="usanum" placeholder="123-456-7890"/>
  <input type="submit">
</form>

Live Demo!


Output:


Placeholder Attribute


The input placeholder attribute is used to specify a hint/what the input is for. The placeholder shows inside the input before any value is entered.



<form>
  <input type="text" placeholder="Enter Full Name"/>
</form>

Live Demo!


Output:


required Attribute


The required attribute is used to make it a must for the user to enter a value in the required input in order to submit the form.



<form action="handle_email.php" method="post">
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" required />
  <input type="submit">
</form>

Live Demo!


Output:


step Attribute


The input's step attribute is used to specify intervals/steps for an input. This attribute works with number, date, range, datetime-local, month, time and week input types.



<form>
  <label for="incNum">Number:</label>
  <input type="number" id="incNum" name="incNum" step="3" />
</form>

Live Demo!


Output:


autofocus Attribute


The autofocus attribute is used when the input field is to be focused on when the page loads.



<form action="handle_name.php" method="post">
  <label for="firstName">First name:</label><br />
  <input type="text" id="firstName" name="firstName" autofocus required/><br />
  <label for="lastName">Last name:</label><br />
  <input type="text" id="lastName" name="lastName" required/><br />
  <input type="submit" value="Submit" />
</form>

Live Demo!


Output:


list Attribute


The list attribute is used to refer to a datalist element in which some options are predefined for the used to select from.



<form>
  <input list="drinks" />
  <datalist id="drinks">
    <option value="Coke"></option>
    <option value="Beer"></option>
    <option value="Milk"></option>
    <option value="Coffee"></option>
    <option value="Tea"></option>
  </datalist>
</form>

Live Demo!


Output: