HTML: Input Tag
work in progressHTML Input tutorial
ai generated
HTML <input> Tag Tutorial
The <input> tag is one of the most important and versatile elements in HTML forms. It creates interactive controls for users to enter data — text, numbers, dates, files, choices, and more.
Basic Syntax
<input type="text" name="username" id="username" placeholder="Enter your name">
- It is a self-closing tag (no closing
</input>needed).
The type Attribute (Most Important)
This determines what kind of input control is shown.
| Type | Purpose | Example |
|---|---|---|
text |
Single-line text | Default |
password |
Hidden characters | Login forms |
email |
Email validation | Contact info |
number |
Numeric input with spinner | Quantity |
tel |
Telephone number | Phone |
url |
Web address | Website |
search |
Search field (often with clear button) | Search bars |
date |
Date picker | Birthdate |
time |
Time picker | Appointment |
datetime-local |
Date + time | Event scheduling |
month / week |
Month or week picker | Billing |
color |
Color picker | Design tools |
checkbox |
Toggle (yes/no) | Options |
radio |
Select one from group | Gender |
file |
File upload | Attachments |
range |
Slider | Volume, price |
hidden |
Not visible to user | CSRF (Cross-Site Request Forgery) tokens |
submit |
Submit button | Form submission |
reset |
Reset form | Clear all fields |
button |
Generic clickable button | Custom JS actions |
Common Attributes
| Attribute | Description | Example |
|---|---|---|
name |
Name sent to server with form data | name="email" |
id |
Unique identifier for CSS/JS | id="email" |
value |
Pre-filled value | value="John" |
placeholder |
Hint text that disappears on focus | placeholder="your@email.com" |
required |
Makes field mandatory | required |
readonly |
User cannot edit | readonly |
disabled |
Grayed out and not submittable | disabled |
autofocus |
Automatically focused on page load | autofocus |
autocomplete |
Enable/disable browser suggestions | autocomplete="off" |
min / max |
For number, range, date | min="18" max="100" |
step |
Increment for number/range | step="0.5" |
pattern |
Regex validation | pattern="[A-Za-z]{3,}" |
maxlength |
Maximum characters | maxlength="50" |
size |
Visible width (characters) | size="30" |
multiple |
Allow multiple selections (file, email) | multiple |
accept |
File types allowed | accept="image/*" |
Practical Examples
1. Basic Login Form
<form> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br><br> <input type="submit" value="Login"> </form>
2. Registration Form with Various Types
<form> <label>Full Name: <input type="text" name="fullname" required></label><br> <label>Age: <input type="number" name="age" min="13" max="120"></label><br> <label>Birthday: <input type="date" name="birthdate"></label><br> <label>Website: <input type="url" name="website"></label><br> <label> <input type="checkbox" name="newsletter" checked> Subscribe to newsletter </label><br> <fieldset> <legend>Gender</legend> <label><input type="radio" name="gender" value="male"> Male</label> <label><input type="radio" name="gender" value="female"> Female</label> </fieldset> <label>Profile Picture: <input type="file" name="photo" accept="image/*"></label><br> <input type="submit" value="Register"> </form>
3. Range Slider with Live Value
<label>Volume: <input type="range" id="volume" min="0" max="100" value="50"></label> <output id="volumeValue">50</output> <script> const slider = document.getElementById('volume'); const output = document.getElementById('volumeValue'); slider.addEventListener('input', () => output.value = slider.value); </script>
Styling Tips
input { padding: 10px; border: 2px solid #ccc; border-radius: 4px; font-size: 16px; } input:focus { outline: none; border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.2); } input[type="checkbox"], input[type="radio"] { width: auto; }
Best Practices
-
Always use labels — improves accessibility and click area.
<label for="username">Username</label> <input id="username" ...> -
Group related inputs with
<fieldset>and<legend>. -
Provide clear validation messages using JavaScript or HTML5 validation.
-
Use
autocompletewisely for better UX on forms users fill often. -
Test on mobile — many input types (date, email, tel) trigger special keyboards.
-
Accessibility: Add
aria-describedbyfor extra help text.
HTML5 Validation Example
<input type="email" required pattern=".+@.+\..+">
ai generated
JavaScript DOM Tutorial: Input Text Fields
This tutorial covers everything you need to know about working with <input type="text"> (and similar text inputs like email, password, search, etc.) using the JavaScript DOM.
1. HTML Setup
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Input Text Field Tutorial</title> </head> <body> <label for="username">Username:</label> <input type="text" id="username" placeholder="Enter your username" /> <button id="submitBtn">Submit</button> <div id="output"></div> <script src="script.js"></script> </body> </html>
Common input types:
type="text"— standard texttype="email"— email validation hinttype="password"— masked inputtype="search"— search fieldtype="url"/tel— specialized keyboards on mobile
2. Accessing the Input Element
// Most common ways const input = document.getElementById('username'); const input2 = document.querySelector('#username'); const input3 = document.querySelector('input[type="text"]'); // All inputs of a type const allTextInputs = document.querySelectorAll('input[type="text"]');
3. Reading and Setting the Value
// Get value console.log(input.value); // current text // Set value input.value = "Xah Lee"; // Clear the field input.value = ""; // Get value with trimming (very common) const cleanValue = input.value.trim();
4. Key Properties
input.placeholder = "Type here..."; input.disabled = true; // prevents editing input.readOnly = true; // allows selection but not editing input.maxLength = 20; // character limit input.size = 30; // visual width in characters input.required = true; // for form validation
5. Important Events
input.addEventListener('input', () => { // Fires every time the value changes (best for live updates) console.log('Current value:', input.value); }); input.addEventListener('change', () => { // Fires when the field loses focus AND value changed console.log('Value changed to:', input.value); }); input.addEventListener('focus', () => { console.log('Input focused'); }); input.addEventListener('blur', () => { console.log('Input lost focus'); }); input.addEventListener('keydown', (e) => { console.log('Key pressed:', e.key); if (e.key === 'Enter') { console.log('User pressed Enter'); } });
6. Complete Practical Example
const usernameInput = document.getElementById('username'); const submitBtn = document.getElementById('submitBtn'); const output = document.getElementById('output'); function updateOutput() { const name = usernameInput.value.trim(); if (name === '') { output.textContent = 'Please enter a username'; output.style.color = 'red'; } else { output.textContent = `Hello, ${name}!`; output.style.color = 'green'; } } // Live update as user types usernameInput.addEventListener('input', updateOutput); // Submit button submitBtn.addEventListener('click', () => { updateOutput(); // Optional: focus back to input usernameInput.focus(); }); // Bonus: Submit on Enter key usernameInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { submitBtn.click(); } });
7. Form Validation Examples
// Basic validation function validateInput() { const value = usernameInput.value.trim(); if (value.length < 3) { usernameInput.style.borderColor = 'red'; return false; } else { usernameInput.style.borderColor = 'green'; return true; } } // Real-time validation usernameInput.addEventListener('input', validateInput);
8. Working with Multiple Inputs
const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // prevent page reload const formData = new FormData(form); for (const [key, value] of formData) { console.log(`${key}: ${value}`); } });
9. Advanced Tips
// Select all text when focused input.addEventListener('focus', () => { input.select(); }); // Clear button (common UX pattern) const clearBtn = document.createElement('button'); clearBtn.textContent = 'Clear'; clearBtn.addEventListener('click', () => { input.value = ''; input.focus(); }); // Debounce input (useful for search) let timeout; input.addEventListener('input', () => { clearTimeout(timeout); timeout = setTimeout(() => { console.log('Search term:', input.value); }, 300); });
Quick Reference
| Property/Method | Purpose |
|---|---|
.value |
Get/set text content |
.placeholder |
Hint text |
.disabled |
Disable editing |
.readOnly |
Read-only mode |
.focus() |
Focus the input |
.select() |
Select all text |
.blur() |
Remove focus |
Best Practice: Always use id or specific selectors. Prefer the input event for live updates and change when you only need final value.
Would you like me to expand this tutorial with sections on:
- Password visibility toggle?
- Autocomplete / datalist?
- File input handling?
- Custom styled inputs with contenteditable?
file
<input type="file" />
hidden
<input type="hidden" />
date
<input type="date" />
datetime-local
<input type="datetime-local" />
<input type="email" />
image
<input type="image" />
month
<input type="month" />
search
<input type="search" />
tel
<input type="tel" />
time
<input type="time" />
url
<input type="url" />
week
<input type="week" />
Submit Buttons
INPUT with attribute type="submit" draws submit buttons. When these buttons are pressed, the form is sent to the CGI program. The name and value attributes are optional.
Submit button 1:
<input type="submit" name="submit1">
Multiple Submit Buttons
You can have multiple submit buttons, with name and
value attributes. The name attribute can be
the same. The value of the value will be shown as the
text on button, and is the value string sent to the server.
<input type="submit" name="license_agreement" value="agree"> <input type="submit" name="license_agreement" value="disagree">
Reset Button
The type="reset" shows a button with a special action that tells the browser to reset the form.
<input type="reset" name="reset" value="Reset">