Javascript

If Statements: Clearing Form Fields

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

html
<form id="myForm">
<input type="text" id="myInput" value="clear me" />
<button type="button" id="clearBtn">Clear if needed</button>
</form>

JavaScript with If Statement to Clear Field

js
const input = document.getElementById('myInput');
const button = document.getElementById('clearBtn');

button.addEventListener('click', () => {
if (input.value === "clear me") {
input.value = ""; // Clear the input field
alert("Input cleared!");
} else {
alert("Input not cleared because it doesn't match the condition.");
}
});


How It Works

  • When you click the button:

    • The if statement checks if the input’s current value equals "clear me".

    • If yes, it sets input.value to 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:

js
const inputs = document.querySelectorAll('#myForm input');

function clearNonEmptyFields() {
inputs.forEach(input => {
if (input.value.trim() !== "") {
input.value = "";
}
});
}

document.getElementById('clearBtn').addEventListener('click', clearNonEmptyFields);


Summary

  • Use if statements to conditionally clear form fields.

  • Check the field’s .value to decide whether to clear.

  • This keeps user input safe unless your condition matches.

Leave a Reply

Your email address will not be published. Required fields are marked *