Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to provide new line in JavaScript alert box?
To add a new line in JavaScript alert box, use the "
" escape character:
Syntax
alert("First line\nSecond line");
Basic Example
<html>
<head>
<script>
function showAlert() {
alert("This is line one\nThis is line two\nThis is line three");
}
</script>
</head>
<body>
<button onclick="showAlert()">Click to Show Alert</button>
</body>
</html>
Multiple Line Breaks
You can use multiple "
" characters to create larger spacing between lines:
<html>
<head>
<script>
function showMultiLineAlert() {
alert("Header Text<br>\nBody content here<br>\nFooter information");
}
</script>
</head>
<body>
<button onclick="showMultiLineAlert()">Show Multi-line Alert</button>
</body>
</html>
Practical Use Cases
Common scenarios where multi-line alerts are useful:
<html>
<head>
<script>
function validateForm() {
let errors = [];
// Simulate form validation
errors.push("Name is required");
errors.push("Email format is invalid");
errors.push("Phone number is missing");
if (errors.length > 0) {
alert("Please fix the following errors:<br><br>" + errors.join("<br>"));
}
}
function showInstructions() {
alert("Instructions:<br><br>1. Fill in all required fields<br>2. Click Submit<br>3. Wait for confirmation<br>\nThank you!");
}
</script>
</head>
<body>
<button onclick="validateForm()">Validate Form</button>
<button onclick="showInstructions()">Show Instructions</button>
</body>
</html>
Key Points
- Use "
" to create line breaks in alert messages - Multiple "
" characters create larger gaps between lines - Works consistently across all browsers
- Useful for error messages, instructions, and formatted text
Conclusion
The "
" escape character is the standard way to add line breaks in JavaScript alert boxes. Use it to create more readable and organized alert messages for better user experience.
Advertisements
