Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to make my textfield empty after button click in JavaScript?
To clear a text field after a button click in JavaScript, you can use the onclick event with document.getElementById().value = '' to reset the input field's value to an empty string.
Syntax
document.getElementById("fieldId").value = '';
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Text Field Example</title>
</head>
<body>
<input type="text" id="txtBox" placeholder="Enter some text...">
<button type="button" onclick="clearTextField()">Clear Text</button>
<script>
function clearTextField() {
console.log("Current value: " + document.getElementById('txtBox').value);
document.getElementById('txtBox').value = '';
console.log("Field cleared!");
}
</script>
</body>
</html>
Output
When you enter text in the input field and click the "Clear Text" button, the field will be emptied and the console will show:
Current value: your entered text Field cleared!
Alternative Methods
You can also clear text fields using these approaches:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="field1" placeholder="Method 1">
<button onclick="method1()">Clear Method 1</button><br><br>
<input type="text" id="field2" placeholder="Method 2">
<button onclick="method2()">Clear Method 2</button><br><br>
<input type="text" id="field3" placeholder="Method 3">
<button onclick="method3()">Clear Method 3</button>
<script>
// Method 1: Using value property
function method1() {
document.getElementById('field1').value = '';
}
// Method 2: Using setAttribute
function method2() {
document.getElementById('field2').setAttribute('value', '');
}
// Method 3: Using reset on form
function method3() {
document.getElementById('field3').value = '';
}
</script>
</body>
</html>
Key Points
- Use
document.getElementById().value = ''for the most reliable method - The
onclickattribute calls the JavaScript function when clicked - You can clear multiple fields by calling the function for each field ID
- Always ensure your input field has a unique
idattribute
Conclusion
Clearing text fields in JavaScript is straightforward using document.getElementById().value = ''. This method works reliably across all modern browsers and provides immediate visual feedback to users.
Advertisements
