How do you make JavaScript send http get every time you enter a digit on input. (On input change doesn’t work)
Current Code only sends the request when user changes the input and leaves the field.
**HTML**
<input id="total" name="total" type="number" required>
<span id="converted"></span>
**JS**
var total = document.getElementById("total");
var converted = document.getElementById("converted");
total.addEventListener("change", function() {
fetch("http://localhost:8000/api/convert/"+total.value)
.then(function(response) {
return response.json()
})
.then(function(data) {
cconverted.innerHTML = data.converted;
});
});
2
Answers
Well,
change
event is probably not what you think it is. Basically it fires on "blur" aka changing focus from your input. What you want to hook into isinput
event. Here you can read about deep explanation of "change" event LINKHowever I don’t think sending http request for every user input is a good idea. I would suggest using some
debounce
effect on it.To listen to the event without a delay, use
$(...).on('input change', () => {...})
(provided you have jquery)
Perhaps
document.getElementById("...").addEventListener('input change', () => {...})
will work too, but i didn’t check it.To do what you want to do, listen to the event using one of the listed approaches and perform the request with
fetch
.On a side note, performing a lot of requests when user is editing the input would be bad for server performance and could possibly trigger rate limits. In my opinion, it would be best practice if you’d put a reload button near the input which triggers the API call (from both performance and UX points of view)