Hi,
i would like to add ‘clear’ or ‘X’ button in the searchbar on my website. But this button should clear the form to zero like not used before. At this moment i delete the input text with backspace on keybord. When deleting finished filter content return to zero. Before opening this post i’ve added some codes with html and javascript but it doesn’t work correctly, input text can be deleted but filtering can’t reset.
This is the my code on codepen: https://codepen.io/eyupdmg/pen/LYXWVrM
and this is the website: https://www.broodjes-lemano.be/
Hi @EDemirgil
I am not sure about it but you can try this.
To add a clear button to your search bar that resets the form to its initial state, you can modify your existing code with some JavaScript logic. Here’s an updated version of your code that achieves this functionality:
HTML:
```html
<div class=“searchbar”>
<input type=“text” id=“searchInput” placeholder=“Search…” />
<button id=“clearButton” onclick=“clearSearch()”>X</button>
</div>
```
Javascript:
```javascript
function clearSearch() {
var input = document.getElementById(“searchInput”);
input.value = “”; // Clear the input text
// Call the filter function to reset the content to its initial state
filterItems(“”);
}
function filterItems(searchTerm) {
var items = document.getElementsByClassName(“product-item”);
for (var i = 0; i < items.length; i++) {
var item = items[i];
var itemName = item.getAttribute(“data-name”).toLowerCase();
if (itemName.includes(searchTerm.toLowerCase())) {
item.style.display = “block”; // Display the item
} else {
item.style.display = “none”; // Hide the item
}
}
}
// Initialize the search functionality
var searchInput = document.getElementById(“searchInput”);
searchInput.addEventListener(“input”, function() {
filterItems(this.value);
});
```
With these modifications, clicking on the clear button (X) will clear the search input and call the `filterItems` function with an empty string, effectively resetting the content to its initial state.
Please note that you may need to adjust the styling and positioning of the clear button to match your design requirements.
You can replace your existing code with the updated HTML and JavaScript code provided above to achieve the desired functionality.
Hope this will helps you out. Please mark it as Solution Accepted to help other Community member. Thanks!
Thank you so much. It’s work now.