Skip to content

Commit cbb0fa2

Browse files
Focus, Input Handling
1 parent c80ad11 commit cbb0fa2

File tree

3 files changed

+382
-0
lines changed

3 files changed

+382
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Form Interaction Example</title>
7+
</head>
8+
<body>
9+
10+
<h1>Interactive Form Example</h1>
11+
12+
<!-- Text input that will be focused automatically when the page loads -->
13+
<p>
14+
<label for="name">Name:</label>
15+
<input type="text" id="name" value="John Doe">
16+
</p>
17+
18+
<!-- Password input -->
19+
<p>
20+
<label for="password">Password:</label>
21+
<input type="password" id="password" value="secret">
22+
</p>
23+
24+
<!-- Checkbox for background color change -->
25+
<p>
26+
<label for="purple">Make this page purple:</label>
27+
<input type="checkbox" id="purple">
28+
</p>
29+
30+
<!-- Radio buttons for selecting background color -->
31+
<p>Choose a background color:</p>
32+
<label><input type="radio" name="color" value="orange"> Orange</label>
33+
<label><input type="radio" name="color" value="lightgreen"> Light Green</label>
34+
<label><input type="radio" name="color" value="lightblue"> Light Blue</label>
35+
36+
<!-- File input -->
37+
<p>
38+
<label for="fileUpload">Upload a file:</label>
39+
<input type="file" id="fileUpload">
40+
</p>
41+
42+
<!-- Textarea for comments -->
43+
<p>
44+
<label for="comments">Comments:</label>
45+
<textarea id="comments">This is a comment.</textarea>
46+
</p>
47+
48+
<!-- Submit button -->
49+
<button id="submitBtn">Submit</button>
50+
51+
<!-- Paragraph to display form data -->
52+
<h2>Form Data:</h2>
53+
<p id="formData"></p>
54+
55+
<script src="script.js"></script>
56+
</body>
57+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
# Focus, Input Handling 🎨
2+
3+
This example demonstrates how to create an interactive HTML form using JavaScript. We'll cover topics such as **automatically focusing on input fields**, handling **form submissions**, using **checkboxes and radio buttons** to change the background color, and tracking the length of input fields in **real time**.
4+
5+
## 🛠️ Technologies Used:
6+
- **HTML** for structuring the form elements.
7+
- **JavaScript** for handling form interactions and dynamic behavior.
8+
9+
10+
## 📋 Key Features:
11+
1. **Auto-Focusing Input Fields**: The `focus()` method is used to automatically focus on the name field when the page loads, allowing users to start typing immediately.
12+
2. **Form Submission Handling**: JavaScript collects all the form data and displays it without refreshing the page.
13+
3. **Checkbox Interaction**: A checkbox controls whether the background color of the page should be purple.
14+
4. **Radio Button Selection**: Radio buttons allow users to choose a background color (Orange, Light Green, or Light Blue), and the page background changes accordingly.
15+
5. **File Input Handling**: Users can upload a file, and its name is displayed once selected.
16+
6. **Real-Time Input Length Tracking**: The length of the text in the "Name" input field is tracked in real time.
17+
18+
## 🚀 Getting Started:
19+
20+
1. **Clone or download the project**.
21+
2. Open the `index.html` file in any modern browser to view the interactive form.
22+
23+
## 📂 Project Structure:
24+
25+
- `index.html`: Contains the HTML form structure.
26+
- `script.js`: Contains the JavaScript code for handling the form interactions.
27+
28+
## 📝 HTML Code:
29+
30+
```html
31+
<!DOCTYPE html>
32+
<html lang="en">
33+
<head>
34+
<meta charset="UTF-8">
35+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
36+
<title>Form Interaction Example</title>
37+
</head>
38+
<body>
39+
40+
<h1>Interactive Form Example</h1>
41+
42+
<!-- Text input that will be focused automatically when the page loads -->
43+
<p>
44+
<label for="name">Name:</label>
45+
<input type="text" id="name" value="John Doe">
46+
</p>
47+
48+
<!-- Password input -->
49+
<p>
50+
<label for="password">Password:</label>
51+
<input type="password" id="password" value="secret">
52+
</p>
53+
54+
<!-- Checkbox for background color change -->
55+
<p>
56+
<label for="purple">Make this page purple:</label>
57+
<input type="checkbox" id="purple">
58+
</p>
59+
60+
<!-- Radio buttons for selecting background color -->
61+
<p>Choose a background color:</p>
62+
<label><input type="radio" name="color" value="orange"> Orange</label>
63+
<label><input type="radio" name="color" value="lightgreen"> Light Green</label>
64+
<label><input type="radio" name="color" value="lightblue"> Light Blue</label>
65+
66+
<!-- File input -->
67+
<p>
68+
<label for="fileUpload">Upload a file:</label>
69+
<input type="file" id="fileUpload">
70+
</p>
71+
72+
<!-- Textarea for comments -->
73+
<p>
74+
<label for="comments">Comments:</label>
75+
<textarea id="comments">This is a comment.</textarea>
76+
</p>
77+
78+
<!-- Submit button -->
79+
<button id="submitBtn">Submit</button>
80+
81+
<!-- Paragraph to display form data -->
82+
<h2>Form Data:</h2>
83+
<p id="formData"></p>
84+
85+
<script src="script.js"></script>
86+
</body>
87+
</html>
88+
```
89+
90+
## 📜 JavaScript Code (`script.js`):
91+
92+
```javascript
93+
// Automatically focus on the name input field when the page loads
94+
document.querySelector("#name").focus();
95+
96+
// Function to handle form data and display it
97+
function handleSubmit() {
98+
// Get the values from form fields
99+
const name = document.getElementById('name').value;
100+
const password = document.getElementById('password').value;
101+
const isPurpleChecked = document.getElementById('purple').checked;
102+
const selectedRadioButton = document.querySelector('input[name="color"]:checked');
103+
const selectedColor = selectedRadioButton ? selectedRadioButton.value : 'None';
104+
const fileUpload = document.getElementById('fileUpload').files[0] ? document.getElementById('fileUpload').files[0].name : 'No file selected';
105+
const comments = document.getElementById('comments').value;
106+
107+
// Display the form data
108+
document.getElementById('formData').innerText = `
109+
Name: ${name}\n
110+
Password: ${password}\n
111+
Background Color (Purple): ${isPurpleChecked ? 'Yes' : 'No'}\n
112+
Selected Color: ${selectedColor}\n
113+
Uploaded File: ${fileUpload}\n
114+
Comments: ${comments}
115+
`;
116+
}
117+
118+
// Listen for form submission
119+
document.getElementById('submitBtn').addEventListener('click', handleSubmit);
120+
121+
// Checkbox interaction to change background color
122+
document.getElementById('purple').addEventListener('change', () => {
123+
document.body.style.background = document.getElementById('purple').checked ? 'mediumpurple' : '';
124+
});
125+
126+
// Radio buttons to change background color based on selection
127+
let colorButtons = document.querySelectorAll('input[name="color"]');
128+
colorButtons.forEach(button => {
129+
button.addEventListener('change', () => {
130+
document.body.style.background = button.value;
131+
});
132+
});
133+
134+
// Track the length of the name input field in real time
135+
document.getElementById('name').addEventListener('input', () => {
136+
console.log(`Name length: ${document.getElementById('name').value.length}`);
137+
});
138+
```
139+
140+
## 📝 Detailed Explanations:
141+
### 1. **Automatically Focusing the Name Field** 🔍
142+
143+
```javascript
144+
document.querySelector("#name").focus();
145+
```
146+
147+
- **What It Does**: This line of code selects the input field with the `id="name"` and focuses it automatically when the page loads.
148+
- **Why It’s Useful**: This ensures that when the page loads, the user can start typing in the name field without having to click on it manually. It improves the user experience.
149+
150+
---
151+
152+
### 2. **Handling Form Data Submission Without Page Refresh** 📝
153+
154+
```javascript
155+
function handleSubmit() {
156+
// Collect form values
157+
const name = document.getElementById('name').value;
158+
const password = document.getElementById('password').value;
159+
const isPurpleChecked = document.getElementById('purple').checked;
160+
const selectedRadioButton = document.querySelector('input[name="color"]:checked');
161+
const selectedColor = selectedRadioButton ? selectedRadioButton.value : 'None';
162+
const fileUpload = document.getElementById('fileUpload').files[0] ? document.getElementById('fileUpload').files[0].name : 'No file selected';
163+
const comments = document.getElementById('comments').value;
164+
165+
// Display form data
166+
document.getElementById('formData').innerText = `
167+
Name: ${name}\n
168+
Password: ${password}\n
169+
Background Color (Purple): ${isPurpleChecked ? 'Yes' : 'No'}\n
170+
Selected Color: ${selectedColor}\n
171+
Uploaded File: ${fileUpload}\n
172+
Comments: ${comments}
173+
`;
174+
}
175+
```
176+
177+
- **What It Does**:
178+
- This function is triggered when the user clicks the **Submit** button.
179+
- It **collects** the values from various form fields (name, password, checkbox, radio buttons, file upload, and comments) using `getElementById` and `querySelector`.
180+
- It **displays** the collected form data inside the `<p>` element with the `id="formData"` by updating its `innerText`.
181+
182+
- **Why There Is No Page Refresh**:
183+
- Normally, submitting a form triggers a page refresh or navigation. However, in this case, the **Submit** button is **not inside a form element** with a default `submit` action. Instead, we are manually attaching a `click` event listener to the button, which prevents the form from submitting traditionally and reloading the page.
184+
- The form data is handled **entirely by JavaScript** using the `click` event, which means the form behaves dynamically without needing to refresh the page.
185+
186+
- **Displaying Data**: After collecting the form values, the `innerText` of the `#formData` element is updated with the captured information. This is how the form data is displayed back to the user without refreshing the page.
187+
188+
---
189+
190+
### 3. **Listening for the Submit Button Click Event** 🖱️
191+
192+
```javascript
193+
document.getElementById('submitBtn').addEventListener('click', handleSubmit);
194+
```
195+
196+
- **What It Does**: This code adds an event listener to the **Submit** button (`id="submitBtn"`). When the button is clicked, it triggers the `handleSubmit()` function, which collects and displays the form data.
197+
198+
- **No Default Form Submission**: Since this is a `click` event listener, it overrides the traditional behavior of form submission. Normally, submitting a form would refresh the page, but since we're using JavaScript to handle the submission manually, there is no page refresh.
199+
200+
---
201+
202+
### 4. **Changing Background Color with a Checkbox** 🌈
203+
204+
```javascript
205+
document.getElementById('purple').addEventListener('change', () => {
206+
document.body.style.background = document.getElementById('purple').checked ? 'mediumpurple' : '';
207+
});
208+
```
209+
210+
- **What It Does**: This code listens for changes in the checkbox with the `id="purple"`. When the user checks or unchecks the box:
211+
- If checked, the background color of the page changes to **purple**.
212+
- If unchecked, the background color resets to its original color (an empty string).
213+
214+
- **Why It’s Useful**: This dynamic interaction allows users to control the background color of the page using a checkbox, which is a common feature for customizing the look of web pages.
215+
216+
---
217+
218+
### 5. **Handling Radio Button Changes** 🎨
219+
220+
```javascript
221+
let colorButtons = document.querySelectorAll('input[name="color"]');
222+
colorButtons.forEach(button => {
223+
button.addEventListener('change', () => {
224+
document.body.style.background = button.value;
225+
});
226+
});
227+
```
228+
229+
- **What It Does**:
230+
- This code selects all radio buttons with the `name="color"`.
231+
- It adds an event listener to each radio button, and when one is selected, the background color of the page changes to the value of the selected radio button (either **orange**, **light green**, or **light blue**).
232+
233+
- **Why It’s Useful**: Radio buttons are used to allow the user to select only **one option** from a group. This example lets the user dynamically change the page's background color based on their selection of a radio button.
234+
235+
---
236+
237+
### 6. **Tracking Real-Time Input Length** 📏
238+
239+
```javascript
240+
document.getElementById('name').addEventListener('input', () => {
241+
console.log(`Name length: ${document.getElementById('name').value.length}`);
242+
});
243+
```
244+
245+
- **What It Does**:
246+
- This code listens for the `input` event on the **name input field** (`id="name"`). The `input` event is triggered every time the user types, deletes, or modifies the text in the input field.
247+
- It logs the length of the text inside the input field in real time to the console using `console.log()`.
248+
249+
- **Why It’s Useful**: Tracking input length is useful for form validation, such as ensuring that the user’s name or password meets certain length requirements. In this case, it simply logs the length of the name field to the console, but it could be expanded to show validation messages if necessary.
250+
251+
---
252+
253+
### **How the Form Submission Works Without Page Refresh** 🚫🔄
254+
255+
In a traditional HTML form, pressing a **submit button** inside a `<form>` tag would cause the browser to:
256+
1. **Submit the form data** to the server (via a `GET` or `POST` request).
257+
2. **Reload the page** with either the result or the form action URL.
258+
259+
However, in this example:
260+
- The **Submit** button is **not inside a `<form>` tag**, and we are not relying on the default HTML form submission process.
261+
- Instead, we attach a **JavaScript event listener** to the **Submit** button (`click` event) that:
262+
- **Prevents the default form submission behavior**.
263+
- **Handles the form data dynamically** within the browser using JavaScript (i.e., collects the input values, processes them, and displays the result).
264+
265+
This approach is called **AJAX-like form handling**, where the form is processed on the client side (in the browser) without reloading the page.
266+
267+
---
268+
269+
## **Summary** of Key Concepts
270+
271+
1. **Focus Management**: The `focus()` method automatically focuses the name input field when the page loads.
272+
2.
273+
274+
**Form Handling Without Page Refresh**: Instead of submitting the form traditionally, we use JavaScript's `click` event on the Submit button to handle the form data dynamically and prevent page refresh.
275+
3. **Dynamic Background Changes**:
276+
- The **checkbox** toggles the page's background to purple.
277+
- **Radio buttons** change the background color to **orange**, **light green**, or **light blue**.
278+
4. **Real-Time Input Tracking**: The `input` event tracks the length of the name input field and logs it to the console.
279+
280+
By using **JavaScript** to handle form interactions and submissions, we avoid the need for page refreshes and create a smoother, more dynamic user experience! 🎉
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Automatically focus on the name input field when the page loads
2+
document.querySelector("#name").focus();
3+
4+
// Function to handle form data and display it
5+
function handleSubmit() {
6+
// Get the values from form fields
7+
const name = document.getElementById('name').value;
8+
const password = document.getElementById('password').value;
9+
const isPurpleChecked = document.getElementById('purple').checked;
10+
const selectedRadioButton = document.querySelector('input[name="color"]:checked');
11+
const selectedColor = selectedRadioButton ? selectedRadioButton.value : 'None';
12+
const fileUpload = document.getElementById('fileUpload').files[0] ? document.getElementById('fileUpload').files[0].name : 'No file selected';
13+
const comments = document.getElementById('comments').value;
14+
15+
// Display the form data
16+
document.getElementById('formData').innerText = `
17+
Name: ${name}\n
18+
Password: ${password}\n
19+
Background Color (Purple): ${isPurpleChecked ? 'Yes' : 'No'}\n
20+
Selected Color: ${selectedColor}\n
21+
Uploaded File: ${fileUpload}\n
22+
Comments: ${comments}
23+
`;
24+
}
25+
26+
// Listen for form submission
27+
document.getElementById('submitBtn').addEventListener('click', handleSubmit);
28+
29+
// Checkbox interaction to change background color
30+
document.getElementById('purple').addEventListener('change', () => {
31+
document.body.style.background = document.getElementById('purple').checked ? 'mediumpurple' : '';
32+
});
33+
34+
// Radio buttons to change background color based on selection
35+
let colorButtons = document.querySelectorAll('input[name="color"]');
36+
colorButtons.forEach(button => {
37+
button.addEventListener('change', () => {
38+
document.body.style.background = button.value;
39+
});
40+
});
41+
42+
// Track the length of the name input field in real time
43+
document.getElementById('name').addEventListener('input', () => {
44+
console.log(`Name length: ${document.getElementById('name').value.length}`);
45+
});

0 commit comments

Comments
 (0)