How does inline JavaScript work with HTML ?
Last Updated :
18 Dec, 2023
Inline JavaScript can be achieved by using a Script tag inside the body of the HTML, and instead of specifying the source(src=”…”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag
Syntax:
<script>
// JavaScript Code
</script>
Example: In this example, an HTML document features a form with a name input and a submit button. The inline JavaScript validates the input upon submission, displaying an alert. If the name is empty, it prompts the user; otherwise, it greets them along with a message from GeeksforGeeks.
html
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript</title>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 style="text-align:center;color:green;">
GeeksforGeeks
</h1>
<form>
<div class="form-group">
<label for="">Enter Your Name:</label>
<input id="name"
class="form-control"
type="text"
placeholder="Input Your Name Here">
</div>
<div class="form-group">
<button id="btn-alert"
class="btn btn-success btn-lg float-right"
type="submit">
Submit
</button>
</div>
</form>
</div>
<script>
let user_name = document.getElementById("name");
document.getElementById("btn-alert").addEventListener("click", function(){
let value=user_name.value.trim();
if(!value)
alert("Name Cannot be empty!");
else
alert("Hello, " + value + "!\nGreetings From GeeksforGeeks.");
});
</script>
</body>
</html>