Clearing Form Fields with If Statements in JavaScript
Sometimes, you want to clear or reset form fields only under certain conditions — and that’s where if statements come in handy.
Example Scenario
Let’s say you want to clear an input field only if it contains a specific value (like "clear me"), otherwise leave it as is.
HTML Form Example
JavaScript with If Statement to Clear Field
How It Works
-
When you click the button:
-
The
ifstatement checks if the input’s current value equals"clear me". -
If yes, it sets
input.valueto an empty string"", clearing the field. -
Otherwise, it leaves the input as is and shows a message.
-
Bonus: Clear All Fields if Not Empty
You can also clear multiple fields only if they are not empty:
Summary
-
Use
ifstatements to conditionally clear form fields. -
Check the field’s
.valueto decide whether to clear. -
This keeps user input safe unless your condition matches.
