coding filters & clear input fileds using javascript code-push-1-6

How can you clear an input field in HTML using JavaScript?

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

  1. The user types something into the input field.
  2. When the “Clear” button is clicked, the clearInput function is called.
  3. The function sets the input field’s value to an empty string, effectively clearing it.

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.

Author

  • theaamirlatif

    Frontend Web Dev and UI/UX Engineer, cross-browser, responsive design, user interaction, web accessibility, and client-side optimization in React, WP, Apps Dev.

    View all posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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