Reputation: 1051
i am trying to filter this json API, using regex... i receive some json, when i input some letter for example "j" in input field, i want to return author of quote for instance "jessie", and it works perfectly, but i have problem, if i want to return error alert, if in this json APi there are not author names for letter "f" , what i can to do, i tried everything but can't figure out what happens to me :(
//my HTML looks like this:
<div class="container mt-5" ">
<div class="row">
<div class="col-md-4 m-auto">
<h3 class="text-center mb-3" style="color: rgb(10, 10, 10); font-family: 'Anton', sans-serif;">
Search Characters Quotes by their names
</h3>
<div class="form-grup">
<input type="text" class="imput form-control form-control-lg" title="Only Alphabets" id="search" placeholder="search">
</div>
<div id="match-list"></div>
</div>
</div>
</div>
//my javascript looks same
const search = document.getElementById("search");
const ResultHtml = document.getElementById("match-list");
const request = async () => {
const response = await fetch("https://www.breakingbadapi.com/api/quotes");
const data = await response.json();
renderYourData(data, search.value);
}
const renderYourData = (data, searchtext) => {
const x= data.filter(film=>{
const regex = new RegExp(`^${searchtext}`, 'gi');
return film.author.match(regex)});
function retquote(){
ResultHtml.innerHTML =`<div class="some">${x.map(function(bra){
return `<p>${bra.author}</p>`
}).join("") } </div>`
}
retquote();
}
window.addEventListener('load', function() {
request();
});
search.addEventListener('input',request)
Upvotes: 1
Views: 92
Reputation: 13693
Change your retquote function to check if array length exist, if yes display the results otherwise put a default error message
Demo: https://jsfiddle.net/utnqeLmf/
function retquote() {
if (x.length) {
ResultHtml.innerHTML = `<div class="some">${x.map(function(bra){
return `<p>${bra.author}</p>`
}).join("") } </div>`
} else {
ResultHtml.innerHTML = 'no records found'
}
}
Upvotes: 1