Reputation: 172
Here are the details of the case I want to get some help with:
<section class='result'> </section>
some tags... when the input value found/not found
I create an input to find some text/article, if the input value can't be found, it's gonna show:
sorry can't found
input same value on box searching
And then I try to click the button click again, it repeats that text again and again, when i click the button
many times...
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
Etc...
I just want it to show just once, and when the input changes, it's not gonna repeat again and it's gonna show the new different value: sorry cant... 'new input value'
That is when the input data can't be found, and when the input data is found, after I change the input data in the search box, I want to remove that text sorry cant...
.
And then showing the article data after I found it...
So I want to get some help with how to not repeat them and then insert the new tag after I found the data input by DOM.
Here is the code: https://jsfiddle.net/cornloh/d2Lgkpxe/
const find = el => document.querySelector(el)
const create = el => document.createElement(el)
const lookingThem = find('.searchButton').addEventListener('click', (e) => {
e.preventDefault()
const inputText = find('.box').value.trim();
// console.log(inputText.length);
result(inputText);
})
const result = searching => {
const wikipedia = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=${searching}`; // API
fetch(wikipedia)
.then(resolve => resolve.json())
.then(data => {
if(typeof data.continue === 'undefined'){
displayCantFound(find('.box').value)
} else {
console.log(data);
}
})
.catch((e) => alert('an error occurred', e))
}
const displayCantFound = theInputValue => {
find('.result').insertAdjacentHTML('beforeend',
`<div>
<h3> sorry can't found what you are looking ${theInputValue} </h3>
</div>`)
}
// const displayError = () => {
//
// }
Upvotes: 2
Views: 55
Reputation: 36594
Don't insert new html every time. Just completly replace it.
const displayCantFound = theInputValue => {
find('.result').innerHTML = `<div>
<h3> sorry can't found what you are looking ${theInputValue} </h3>
</div>`
}
If you want error to be removed when the data is found you can replace the following part of code with mine
if(typeof data.continue === 'undefined'){
displayCantFound(find('.box').value)
} else {
console.log(data);
//this line is added
document.querySelector('.result').innerHTML = '';
}
Upvotes: 1