Topics Covered in This JavaScript & JQuery Tutorial:
Mastering If Statements, Implementing Event Handlers, and Strategic JavaScript Placement in HTML Documents
Exercise Preview

Create intelligent form fields that show placeholder text when empty but clear automatically when users interact with them, without requiring manual deletion of placeholder text.
Exercise Overview
In professional web development, you'll frequently need JavaScript code that executes only when specific criteria are met. These conditional statements form the backbone of interactive user experiences. This exercise tackles a common UX challenge: creating intelligent placeholder text in form fields that enhances usability without interfering with user input.
Rather than forcing users to manually delete placeholder text—a friction point that can hurt conversion rates—we'll build a smart system that detects field content and responds appropriately. You'll learn to implement conditional logic that improves the user experience while gaining hands-on experience with event handling and DOM manipulation.
Getting Started
Let's establish your development environment and examine the foundation code we'll be enhancing:
- Open your code editor if it isn't already open.
- Close any files you may have open to maintain focus.
- Navigate to the Form-Fields folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. Consider opening the entire folder in your editor (Visual Studio Code and similar modern editors support this workflow).
- Open form.html from the Form-Fields directory.
- Preview the page in a browser. You'll recognize this as the foundation from the previous exercise—we're building upon established concepts.
- Keep the browser tab open for testing as we iterate through the development process.
- Return to your code editor to begin implementation.
Our first objective is clearing placeholder text from the Name field when users interact with it. We'll use an event handler approach that's more robust than simple page-load triggers.
Add the following code to the nameField input tag on line 25:
<input id="nameField" name="nameField" type="text" class="textfield" value="First and Last Name" onfocus="clearName();">NOTE: We're using onfocus rather than onclick for better accessibility. While onclick only responds to mouse interactions, onfocus triggers when the element receives focus through any method—mouse clicks, keyboard navigation, or assistive technologies. This inclusive approach ensures your interface works for all users.
Now we'll define the function that handles this interaction. Add the script container before the
</head>tag (line 8):<link rel="stylesheet" href="css/main.css"> <script> </script> </head>With the HTML primed to listen for the onfocus event, we'll create the corresponding function. This separation of concerns—HTML handling the event detection, JavaScript managing the behavior—represents clean, maintainable code architecture.
Within the script tag, add:
<script> function clearName() { } </script>We'll leverage the same DOM manipulation techniques from the previous exercise, using getElementById() to target and modify our form field. Add the following code:
function clearName() { document.getElementById('nameField').value = ''; }The empty string assignment ('') effectively clears the field content, providing users with a clean slate for their input.
- Save your changes and reload form.html in your browser.
- Test the functionality by clicking into the Name field (or navigating via Tab). The placeholder text should disappear immediately.
- Enter your name, then navigate to the Phone field to continue testing.
Here's where we discover a critical UX flaw: click back into the Name field and watch your input vanish. This creates user frustration—imagine losing a carefully typed name due to a minor edit attempt.
This behavior demonstrates why thorough testing is essential in web development. Let's implement a more intelligent solution.
Setup Requirements
Start with a clean workspace to avoid confusion
Essential file structure for the exercise
Allows real-time testing of your JavaScript changes
Enables quick refresh to see code changes
Using If Statements
The solution lies in conditional logic—code that evaluates context before taking action. We'll modify our function to clear text only when it matches the original placeholder, preserving user input in all other cases.
- Return to your code editor to implement the conditional logic.
Wrap the clearing logic in an if statement that evaluates the current field content:
function clearName() { if () { document.getElementById('nameField').value = ''; } }Now we'll define the condition. Copy the field-targeting code and paste it into the parentheses:
function clearName() { if (document.getElementById('nameField').value = '') { document.getElementById('nameField').value = ''; } }This is a crucial distinction in programming: change the single equal sign to a double equal sign. In JavaScript:
- Single = assigns values (creates change)
- Double == compares values (tests for equality)
Update your code:
if (document.getElementById('nameField').value == '') {- Locate and copy the placeholder text First and Last Name from the nameField input tag around line 31.
Replace the empty string in your condition with the actual placeholder text:
if (document.getElementById('nameField').value == 'First and Last Name') {Pro tip: Copy-paste prevents typos that can lead to hours of debugging frustration. Even experienced developers use this strategy to avoid simple but costly errors.
- Save, switch to your browser, and reload form.html.
- Test by entering your name in the Name field.
Navigate away and back to the Name field. Your input should persist—the clearing behavior now only occurs when the field contains the original placeholder text. This represents user-centered design in action.
Now let's extend this improved functionality to additional form fields:
- Return to your code editor to implement similar logic for the phone field.
Select and copy the entire clearName() function:
function clearName() { if (document.getElementById('nameField').value == 'First and Last Name') { document.getElementById('nameField').value = ''; } }- Paste the function directly below the original to create our template.
Adapt the duplicate for phone functionality by changing name to phone in three locations:
function clearPhone() { if (document.getElementById('phoneField').value == 'First and Last Name') { document.getElementById('phoneField').value = ''; } }- Copy the phone placeholder text example: 212-123-1234 from the phoneField input around line 39.
Update the condition in your clearPhone function:
if (document.getElementById('phoneField').value == 'example: 212-123-1234') {Connect the function to the HTML by adding the onfocus event to the phone field:
<label for="phoneField">Phone:</label> <input id="phoneField" name="phoneField" type="text" class="textfield" value="example: 212-123-1234" onfocus="clearPhone();">- Save, reload the page, and test both fields to confirm they clear only when containing placeholder text.
Remember that a single equal sign (=) assigns values, while double equal signs (==) compare values. Using the wrong operator will cause your conditional statements to behave unexpectedly.
Reshowing Text Hints in Empty Form Fields
Our current implementation handles the clearing behavior elegantly, but we can enhance the user experience further. When users navigate away from empty fields, restoring the helpful placeholder text provides visual cues and maintains form usability.
- Switch back to your code editor to implement this enhancement.
Copy the entire clearName() function:
function clearName() { if (document.getElementById('nameField').value == 'First and Last Name') { document.getElementById('nameField').value = ''; } }- Paste it directly below to create our reset function template.
Rename the function to reflect its new purpose:
function resetName() {Reverse the logic: instead of clearing when the field contains placeholder text, we'll restore placeholder text when the field is empty:
function resetName() { if (document.getElementById('nameField').value == '') { document.getElementById('nameField').value = 'First and Last Name'; } }Connect this function using the onblur event, which triggers when users leave the field:
<input id="nameField" name="nameField" type="text" class="textfield" value="First and Last Name" onfocus="clearName();" onblur="resetName();">The onblur event is the counterpart to onfocus—it fires when an element loses focus, typically when users click or tab to another field.
- Save and test in your browser. Click into the Name field (placeholder disappears), then navigate to the Phone field (placeholder reappears). This creates a polished, professional user experience.
Let's implement identical functionality for the phone field:
- Return to your code editor and copy the entire clearPhone() function:
Copy the clearPhone() function:
function clearPhone() { if (document.getElementById('phoneField').value == 'example: 212-123-1234') { document.getElementById('phoneField').value = ''; } }- Paste a copy directly below the original.
Rename the duplicate function:
function resetPhone() {Apply the same logic reversal as with the name field:
function resetPhone() { if (document.getElementById('phoneField').value == '') { document.getElementById('phoneField').value = 'example: 212-123-1234'; } }Add the onblur event handler to the phone field:
<input id="phoneField" name="phoneField" type="text" class="textfield" value="example: 212-123-1234" onfocus="clearPhone();" onblur="resetPhone();">- Save and test your completed implementation. Both fields should now clear on focus and restore placeholders when empty and blurred.
Navigate between the Name and Phone fields to confirm the behavior: placeholders disappear during interaction but return to guide users when fields remain empty. User input persists appropriately.
For reference, you can examine the completed code in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Form-Fields.
Event Handler Functions
Feature onfocus onblur When Triggered User enters field User leaves field Our Use Case Clear placeholder text Restore placeholder if empty Function Called clearName() / clearPhone() resetName() / resetPhone() Condition Checked Value equals placeholder Value equals empty string Recommended: Combine both events to create seamless placeholder management that responds to user focus changes.
HTML5 Placeholder Attribute
Modern HTML5 includes a native placeholder attribute that provides similar functionality with less code. However, the JavaScript approach you've just mastered offers several advantages: complete control over behavior, compatibility with legacy browsers, and the ability to customize interactions beyond basic placeholder display. More importantly, you've gained fundamental skills in event handling, conditional logic, and DOM manipulation that apply to countless web development scenarios.
JavaScript vs HTML5 Placeholder
Optional Bonus: Adding a Third Form Field
Ready to reinforce your learning? Challenge yourself to implement an email field using the patterns you've mastered. This exercise will solidify your understanding of the complete workflow:
- HTML Implementation: Create the form field structure using the existing name and phone fields as templates. Pay attention to proper labeling, ID consistency, and event handler attachment.
- JavaScript Functions: Develop both clear and reset functions following the established patterns. Consider what placeholder text would be most helpful for email input (perhaps "your.email@example.com").
This bonus challenge simulates real-world development: taking established patterns and adapting them to new requirements. The skills you practice here—pattern recognition, code replication, and systematic testing—are essential for professional web development success.
Email Field Implementation Guide
Maintains consistent form styling and layout
Use conditional logic to clear only when default value is present
Restores placeholder text when field is left empty
Ensures proper triggering of clear and reset functions
Verify that placeholder management works across all form fields