skip to Main Content

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


  1. 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 is input event. Here you can read about deep explanation of "change" event LINK

      var total = document.getElementById("total");
      total.addEventListener("input", function() {
    
            fetch("http://localhost:8000/api/convert/"+total.value)
            .then(function(response) {
                return response.json()
            })
            .then(function(data) {
                cconverted.innerHTML = data.converted; 
            });
    
        });
    

    However I don’t think sending http request for every user input is a good idea. I would suggest using some debounce effect on it.

    Login or Signup to reply.
  2. 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.

    $('#total').on('input change', () => {
        let el = $('#total');
        fetch('site.com/api?value=' + window.encodeURIComponent(el.text()))
            .then((response) => {
                if (!response.ok())
                    throw new Error(response.status());
                // do what you want with reponse from now on
                // console.log(response)
            }
        ).catch((err) => console.error);
    });
    

    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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search