You can clear an input field in HTML using JavaScript by setting its value
property to an empty string. Here’s how to do it:
Example HTML
#html
<input type="text" id="myInput" value="Some text">
<button onclick="clearInput()">Clear</button>
JavaScript Function
#javascript
function clearInput() {
document.getElementById('myInput').value = '';
}
Full Example
Here’s the complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Clear Input Example</title>
</head>
<body>
<input type="text" id="myInput" value="Some text" class="form-control w-50 ms-4 mt-2 mb-2">
<button onclick="clearInput()" class="btn btn-success w-50 ms-4 mb-2">Clear</button>
<script>
function clearInput() {
document.getElementById('myInput').value = '';
}
</script>
</body>
</html>
How It Works
- The user types something into the input field.
- When the “Clear” button is clicked, the
clearInput
function is called. - The function sets the input field’s value to an empty string, effectively clearing it.
Difficulty in selecting a website design firm? Our complimentary matching service introduces you to pre-screened experts with expertise in your sector, budget and technical specifications for an easy ride.
Related Links!
- How to remove <script> tags from an HTML string in JavaScript?
- How can I add HTML content to Google Docs?
- How can I display viewdata[title] in an HTML document?
- How can I embed HTML code in Canva?
- How to add a video background to a widget using CSS?
Understanding How Coding Filters Help Reduce Complexity!
Coding filters offer a powerful way to reduce complexity by providing a mechanism to focus on relevant data or logic while ignoring unnecessary elements. By applying these filters, developers can avoid convoluted conditional statements, reducing code length and enhancing clarity in their applications.