function GetInfoAboutUser({ button, inputValue, url, elementError }) {
button.addEventListener('click', () => {
// elementError.style.display = 'none'
this.checkInput();
})
this.checkInput = function () {
const regExp = /^([1-9]|[1-9][0-9]|100)$/;
regExp.test(inputValue) ? this.requestPost() : this.showError()
}
this.showError = function () {
elementError.style.display = 'block'
}
this.requestPost = function () {
const promise = fetch(url);
promise
.then(data => {
console.log(data);
return data.json();
})
.then(updateData => {
console.log('Result: ', updateData);
const userInfo = updateData.filter(item => item.id === inputValue);
document.querySelector('.js--userId').innerHTML = `UserId: ${userInfo[0].userId}`
document.querySelector('.js--id').innerHTML = `Id: ${userInfo[0].id}`
document.querySelector('.js--title').innerHTML = `Title: ${userInfo[0].title}`;
document.querySelector('.js--body').innerHTML = `Body: ${userInfo[0].body}`
console.log(userInfo)
})
.catch(err => console.log('Проверьте данные, ',err));
}
}
new GetInfoAboutUser({
button: document.querySelector('.js--button'),
inputValue: document.querySelector('.js--input').value,
url: 'https://jsonplaceholder.typicode.com/posts',
elementError: document.querySelector('.js--small'),
})
<div class="wrapper">
<div class="block__info">
<label>
<input class="js--input" type="text" placeholder="Введите число от 1 до 100">
<small class="js--small">Проверьте корректность ввода данных</small>
</label>
<button class="js--button">Сделать заппрос</button>
</div>
<div class="block__content">
<p class="js--userId"></p>
<p class="js--id"></p>
<p class="js--title"></p>
<p class="js--body"></p>
</div>
</div>
<code lang="css">
p:last-child {
margin-bottom: 0;
}
.block__info {
margin: 0 auto 40px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: flex-start;
}
label {
display: inline-block;
max-width: 400px;
width: 100%;
}
input {
display: block;
padding: 15px 0 15px 15px;
border-radius: 15px;
width: 100%;
border: 2px solid #607D8B;
box-sizing: border-box;
background-color: powderblue;
color: darkblue;
}
input::placeholder {
font-size: 12px;
}
.js--small {
color: red;
display: none;
}
.js--button {
max-width: 200px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
min-height: 50px;
border-radius: 20px;
border: 3px solid darkslateblue;
background-color: azure;
font-size: 13px;
}
</code>
this.checkInput = function () {
const regExp = /^([1-9]|[1-9][0-9]|100)$/;
const inputValue = document.querySelector('.js--input').value; // обновляем переменную inputValue
regExp.test(inputValue) ? this.requestPost() : this.showError();
}