Learning Goals
At the end of this Tutorial, you will be able to:
- Trigger JavaScript functions using the onclick event handler.
- Read data from HTML form fields using the .value property.
- Clean up user input using the .trim() method.
- Validate input to ensure it is not empty or invalid.
- Provide visual feedback (like red borders) when input errors occur.
Setting up your workfiles
For this Tutorial, we need some interactive elements (buttons and inputs) to work with.
In your javascript/exercises folder, create a new HTML file named workfile-7.html and copy the code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Interactivity</title>
<style>
body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
section { margin-bottom: 40px; padding: 20px; background: #f9f9f9; border-radius: 8px;}
input { padding: 8px; font-size: 16px; }
button { padding: 8px 16px; font-size: 16px; cursor: pointer; background: #007bff; color: white; border: none; border-radius: 4px;}
button:hover { background: #0056b3; }
/* Error class for validation */
.input-error { border: 2px solid red; background-color: #ffe6e6; }
</style>
<script defer src="script-7.js"></script>
</head>
<body>
<h1>Interactivity and Input</h1>
<!-- SECTION 1: Simple Button -->
<section>
<h2>1. Event Handlers</h2>
<p id="status-text">Waiting for user...</p>
<button onclick="updateStatus()">Click Me</button>
</section>
<!-- SECTION 2: Text Input -->
<section>
<h2>2. Text Input</h2>
<input type="text" id="user-name" placeholder="Enter your name">
<button onclick="greetUser()">Say Hello</button>
<p id="greeting-msg"></p>
</section>
</body>
</html>
Create a new empty text file named script-7.js and save it in this same folder.
Working with event handlers (Buttons)
A JavaScript function usually sits passively in your code, doing nothing until it is told to run.
To run a function when a user clicks a button, we use the onclick attribute in our HTML. This connects the visual button to the logic in your script file.
Copy this function into your script-7.js file.
// Function to update the status text
function updateStatus() {
// 1. Select the paragraph
const statusPara = document.getElementById("status-text");
// 2. Change the text
statusPara.innerText = "Button has been clicked!";
statusPara.style.color = "green";
}
Save and test your workfile. When you click the "Click Me" button, the text above it should change.
Reading text from input fields
In dynamic web applications, we often need to capture what a user types into a form.
To do this, we select the input element and read its .value property.
Important:
- Use
.innerTextfor elements like paragraphs, headings, and divs. - Use
.valuefor form elements like inputs, textareas, and dropdowns.
Add this code to your script file to handle the second section of your HTML.
// Function to read input and display a greeting
function greetUser() {
// 1. Get the INPUT element
const inputField = document.getElementById("user-name");
// 2. Get the VALUE typed inside it
const name = inputField.value;
// 3. Display it in the paragraph
const msgPara = document.getElementById("greeting-msg");
msgPara.innerText = "Hello, " + name + "!";
}
Test it by typing a name and clicking "Say Hello".
Validating user input
Users often make mistakes. They might leave a box empty or accidentally type just spaces.
Cleaning whitespace with .trim()
If a user types " John ", you usually only want "John". The .trim() method removes any whitespace from the start and end of a string.
Providing visual feedback
If the input is invalid (empty), we should alert the user. In the Setup step, we added a CSS class called .input-error that turns the border red.
Let's update our greetUser function to be smarter.
function greetUser() {
const inputField = document.getElementById("user-name");
const msgPara = document.getElementById("greeting-msg");
// Get value and TRIM extra spaces
const name = inputField.value.trim();
// Check if the name is empty
if (name === "") {
// Error: Make border red and show message
inputField.classList.add("input-error");
msgPara.innerText = "Please enter your name.";
msgPara.style.color = "red";
} else {
// Success: Remove red border and show greeting
inputField.classList.remove("input-error");
msgPara.innerText = "Hello, " + name + "!";
msgPara.style.color = "black";
}
}
Now, if you leave the box empty and click the button, the input field turns red. If you type a name, it goes back to normal.
Working with numeric input
By default, all values retrieved from an HTML input are Strings (text). Even if the user types 25, JavaScript sees it as "25".
If you want to do math with the input, you must convert it to a Number first.
Add this HTML to the bottom of your workfile-7.html body:
<!-- SECTION 3: Number Input -->
<section>
<h2>3. Age Checker</h2>
<input type="number" id="user-age" placeholder="Enter age">
<button onclick="checkAge()">Check Age</button>
<p id="age-msg"></p>
</section>
Now add the JavaScript logic:
function checkAge() {
const ageInput = document.getElementById("user-age");
const ageMsg = document.getElementById("age-msg");
// Convert the string value to a Number
const age = Number(ageInput.value);
// Check if it is a valid number
if (age >= 18) {
ageMsg.innerText = "Access Granted.";
ageMsg.style.color = "green";
} else {
ageMsg.innerText = "You are too young.";
ageMsg.style.color = "red";
}
}
Try it yourself
In your workfile...
---
Tip Calculator: Create an input for "Bill Amount" and a button "Calculate Tip".
When clicked, calculate 15% of the bill and display the result in a paragraph.
---
Dark Mode Toggle: Create a button labeled "Toggle Dark Mode".
When clicked, check if the document body has a specific class (e.g., "dark-theme"). If it does, remove it. If not, add it.
More learning resources
Tutorial Quiz
Tutorial Podcast
Sample AI prompts
I want to create a "Show Password" checkbox. Show me how to use JavaScript to toggle an input field's type between "password" and "text" when a user clicks a checkbox.
Explain how to listen for the "Enter" key being pressed in an input field, so the user can submit the form without clicking the button.