this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
loader.classList.add("display")
fetch(`http://localhost:5050/fibonacci/`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value; // i want to get the input value from the input field and the server to calculate it and present it to the user.
});
});
}
basically what i want to do, is to add the value the user types in to the innerHTML paragraph id name. and then i want to make the button react to the click and re-display the "loader" (which i gave it display:none in the CSS file) and then, i need to make the button to display an error message if the input is higher than 50.
what i have tried to do:
inside the
clcBtn.addEventListener("click", calcFunc); function calcFunc() {
i have tried to add:
loader.classlist.add("display")
and inside
return response.json().then(function (data) { result.innerHTML = data.clcInput.value;
i have tried to add and change it to:
clcInput.value = innerHTML.result;
what am i doing wrong? what is wrong with my syntax and what is the order i need to write everything? thank you!!!
CodePudding user response:
If i understand correctly what is you need, you should look at the small snippets I did below. It show a loader during the API Call and hide it when you get the result as well as updating the info paragraph depending on the value you typed.
The main thing I recommend you changing in order for your code to work properly is not adding or removing a class to your spinner element to hide it and show it, but simply changing directly it's style by using loader.style.display = "value"
Hope it helps.
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
paragraph.innerText= "";
loader.style.display = "block";
// TimeOut to simulate API Call
setTimeout(function() {
loader.style.display = "none";
if (clcInput.value > 50) {
paragraph.innerText = clcInput.value " - Error, value too high";
} else {
paragraph.innerText = clcInput.value " - Value correct";
}
}, 2000);
}
#spinner {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
border: 5px solid black;
display: none;
}
<input type="number" id="calcInput" />
<button id="calcButton">calcButton</button>
<div id="spinner"></div>
<p id="paragraph"></p>