Skip to content

Commit 84e5bdd

Browse files
authored
Update 03. JavaScript Take Input.md
1 parent aaa11a1 commit 84e5bdd

1 file changed

Lines changed: 223 additions & 66 deletions

File tree

03. JavaScript Take Input.md

Lines changed: 223 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,225 @@
1-
# 3. JavaScript Take Input
2-
3-
In JavaScript, you can take input from the user in several ways, depending on the environment in which your code is running. The most common methods for taking user input in JavaScript include:
4-
5-
1. **`prompt()` Method:**
6-
The `prompt()` method displays a dialog box with a message and an input field for the user to enter data. The user's input is captured as a string.
7-
8-
```javascript
9-
let userInput = prompt("Enter your name:");
10-
console.log("Hello, " + userInput);
11-
```
12-
13-
Keep in mind that `prompt()` is a blocking function, and the code execution will pause until the user provides input or closes the dialog.
14-
15-
2. **HTML Input Elements:**
16-
In a web page, you can use HTML input elements like `<input>` and `<textarea>` within a form to collect user input. You can then access the input values using JavaScript.
17-
18-
```html
19-
<input type="text" id="userInput">
20-
<button onclick="getUserInput()">Submit</button>
21-
<script>
22-
function getUserInput() {
23-
let userInput = document.getElementById("userInput").value;
24-
console.log("User input: " + userInput);
25-
}
26-
</script>
27-
```
28-
29-
This example shows an `<input>` element and a button. The `getUserInput()` JavaScript function retrieves the input value when the button is clicked.
30-
31-
3. **Using Event Listeners:**
32-
You can use event listeners to capture user input from various HTML elements, such as text boxes, buttons, and forms.
33-
34-
```html
35-
<input type="text" id="userInput">
36-
<button id="submitButton">Submit</button>
37-
<script>
38-
document.getElementById("submitButton").addEventListener("click", function() {
39-
let userInput = document.getElementById("userInput").value;
40-
console.log("User input: " + userInput);
41-
});
42-
</script>
43-
```
44-
45-
In this example, a click event listener is added to the button, and the input value is obtained when the button is clicked.
46-
47-
4. **Node.js Command-Line Input:**
48-
If you are using JavaScript in a Node.js environment, you can take command-line input using the `readline` module.
49-
50-
```javascript
51-
const readline = require('readline');
52-
const rl = readline.createInterface({
53-
input: process.stdin,
54-
output: process.stdout
55-
});
56-
57-
rl.question('Enter your name: ', (userInput) => {
58-
console.log(`Hello, ${userInput}`);
59-
rl.close();
60-
});
61-
```
62-
63-
This code creates a command-line input prompt, takes user input, and displays a message based on the input.
64-
65-
These are some common methods for taking user input in JavaScript, and the choice of method depends on your specific use case, whether you're working in a web browser environment or a Node.js environment.
66-
671

682

3+
# JavaScript Input Handling
4+
5+
## 1. Input Methods in JavaScript
6+
7+
### 1.1 Browser-Based Input Methods
8+
1. **Prompt Input**
9+
2. **Confirm Input**
10+
3. **Alert Interaction**
11+
4. **HTML Form Inputs**
12+
5. **DOM Element Interaction**
13+
14+
## 2. Prompt Method
15+
### Basic Syntax
16+
```javascript
17+
let userName = prompt("Enter your name:", "John Doe");
18+
```
19+
#### Characteristics
20+
- Simple built-in browser dialog
21+
- Returns user input as a string
22+
- Optional default value
23+
- Returns `null` if user cancels
24+
25+
#### Example
26+
```javascript
27+
// Full prompt example
28+
function greetUser() {
29+
let name = prompt("What's your name?", "Guest");
30+
31+
if (name === null) {
32+
alert("User cancelled input");
33+
} else {
34+
alert(`Hello, ${name}!`);
35+
}
36+
}
37+
```
38+
39+
## 3. Confirm Method
40+
### Basic Syntax
41+
```javascript
42+
let result = confirm("Are you sure?");
43+
```
44+
#### Characteristics
45+
- Returns boolean value
46+
- Shows OK/Cancel dialog
47+
- Used for yes/no decisions
48+
49+
#### Example
50+
```javascript
51+
function deleteItem() {
52+
let confirmation = confirm("Do you want to delete this item?");
53+
54+
if (confirmation) {
55+
console.log("Item deleted");
56+
} else {
57+
console.log("Deletion cancelled");
58+
}
59+
}
60+
```
61+
62+
## 4. HTML Form Inputs
63+
### 4.1 Text Input
64+
```html
65+
<input type="text" id="username" name="username">
66+
<button onclick="processInput()">Submit</button>
67+
68+
<script>
69+
function processInput() {
70+
let username = document.getElementById('username').value;
71+
console.log(username);
72+
}
73+
</script>
74+
```
75+
76+
### 4.2 Number Input
77+
```html
78+
<input type="number" id="age" name="age">
79+
<script>
80+
function validateAge() {
81+
let age = document.getElementById('age').value;
82+
let numAge = Number(age);
83+
84+
if (numAge >= 18) {
85+
console.log("You are an adult");
86+
} else {
87+
console.log("You are a minor");
88+
}
89+
}
90+
</script>
91+
```
92+
93+
## 5. Input Validation Techniques
94+
95+
### 5.1 Basic Validation
96+
```javascript
97+
function validateInput(input) {
98+
// Check if input is empty
99+
if (input.trim() === "") {
100+
alert("Input cannot be empty");
101+
return false;
102+
}
103+
104+
// Check input length
105+
if (input.length < 3) {
106+
alert("Input too short");
107+
return false;
108+
}
109+
110+
return true;
111+
}
112+
```
113+
114+
### 5.2 Regular Expression Validation
115+
```javascript
116+
function validateEmail(email) {
117+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
118+
return emailRegex.test(email);
119+
}
120+
121+
function checkEmail() {
122+
let email = document.getElementById('email').value;
123+
124+
if (validateEmail(email)) {
125+
console.log("Valid email");
126+
} else {
127+
console.log("Invalid email");
128+
}
129+
}
130+
```
131+
132+
## 6. Advanced Input Methods
133+
134+
### 6.1 Event Listeners
135+
```javascript
136+
// Real-time input tracking
137+
let inputField = document.getElementById('realTimeInput');
138+
139+
inputField.addEventListener('input', function(event) {
140+
console.log("Current input:", event.target.value);
141+
});
142+
```
143+
144+
### 6.2 Keyboard Events
145+
```javascript
146+
document.addEventListener('keydown', function(event) {
147+
console.log("Key pressed:", event.key);
148+
149+
// Custom key handling
150+
if (event.key === 'Enter') {
151+
processSubmission();
152+
}
153+
});
154+
```
155+
156+
## 7. Type Conversion Techniques
157+
158+
### 7.1 Conversion Methods
159+
```javascript
160+
let stringInput = "42";
161+
162+
// Convert to Number
163+
let numericValue = Number(stringInput); // 42
164+
let parsedValue = parseInt(stringInput); // 42
165+
let floatValue = parseFloat(stringInput); // 42.0
166+
167+
// Convert to Boolean
168+
let booleanValue = Boolean(stringInput); // true
169+
170+
// Convert to String
171+
let stringValue = String(numericValue); // "42"
172+
```
173+
174+
## 8. Error Handling
175+
```javascript
176+
function safeInputProcess(input) {
177+
try {
178+
// Processing logic
179+
let result = someComplexCalculation(input);
180+
return result;
181+
} catch (error) {
182+
console.error("Input processing error:", error);
183+
return null;
184+
}
185+
}
186+
```
187+
188+
## 9. Security Considerations
189+
1. Always sanitize and validate user inputs
190+
2. Use `trim()` to remove unnecessary whitespaces
191+
3. Implement server-side validation
192+
4. Escape special characters
193+
5. Set input length limits
194+
195+
## 10. Modern Input Techniques
196+
197+
### 10.1 Fetch API with Form Data
198+
```javascript
199+
async function submitForm(event) {
200+
event.preventDefault();
201+
202+
let formData = new FormData(event.target);
203+
let data = Object.fromEntries(formData);
204+
205+
try {
206+
let response = await fetch('/submit', {
207+
method: 'POST',
208+
body: JSON.stringify(data)
209+
});
210+
} catch (error) {
211+
console.error("Submission failed");
212+
}
213+
}
214+
```
215+
216+
## Conclusion
217+
Mastering input handling is crucial for creating interactive web applications. Practice, validate, and always prioritize user experience and security.
218+
219+
**Pro Tips:**
220+
- Validate all inputs
221+
- Provide clear feedback
222+
- Handle edge cases
223+
- Use appropriate input types
224+
225+
**Happy Coding!** 🚀👨‍💻

0 commit comments

Comments
 (0)