I am confusing how can I show an error message when I won't find any data
const getValue = ()=>{
const error = document.getElementById('error')
const searchField = document.getElementById('searchValue')
const searchValue = searchField.value; }
<div class="position">
<div class="d-flex justify-content-center">
<div class="input-group mb-3 w-50">
<input type="text" id="searchValue" class="form-control" placeholder="Search Your Phone" aria-label="Recipient's username" aria-describedby="button-addon2">
<button class="btn btn-outline-secondary" type="button" onclick="getValue()" id="button-addon2">Search</button>
</div>
<p class="text-center error-color" id="error"></p>
</div>
</div>
I'm not exactly sure what you are trying to do, but we can check the length of the string in the input field to display an error message if the user hasn't entered anything.
I renamed some of your functions and tried to make the code a simple as I could to make it easy to read. There are some shortcuts that could be taken. For instance, the clearError function could simply be the setError function with a blank string and the if/else could be simply an if with a return, etc.
window.addEventListener('DOMContentLoaded', (event) => {
const error = document.getElementById('error');
const searchField = document.getElementById('searchValue');
const searchButton = document.getElementById('button-addon2');
const clearError = () => error.innerHTML = "";
const setError = (str) => error.innerHTML = str;
const onSearch = () => {
clearError();
if (searchField.value.length < 1) {
setError("Please enter a search term");
} else {
// ... do some search
}
}
searchButton.addEventListener('click', onSearch);
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="position">
<div class="d-flex justify-content-center">
<div class="input-group mb-3 w-50">
<input type="text" id="searchValue" class="form-control" placeholder="Search Your Phone" aria-label="Recipient's username" aria-describedby="button-addon2">
<button class="btn btn-outline-secondary" type="button" onclick="" id="button-addon2">Search</button>
</div>
</div>
<p class="text-center error-color" id="error"></p>
</div>