skip to Main Content

The title is basically it. I am trying to read the user input in the html element using javascript.

This is not an duplicate to any existing question because numerous existing answers suggested just reading the "value" of the input.

i.e.

const input_value = document.getElementById('input_id').value;

However, this is not correct, when you print the ‘input_value’ it gives you a blank line in the javascript console.

Does anyone know the CORRECT way of reading the content typed by the user.

2

Answers


  1. let input = document.getElementById('input').value;
    

    I use this in the code for a searchbar, it works well

    Login or Signup to reply.
  2. So the code is not wrong but the implementation is.

    The problem

    When you do

    const input_value = document.getElementById('input_id').value;
    

    This means take the current value in the input and store it to the constant `input_value. And since the current value at the start is empty string, empty string is being stored, and even after changing the value in web page, it is not being updated.

    Solution

    The solution is simple. Just store the element in a constant and fetch the value only when needed.

    const input = document.getElementById('input_id'); // this stores the input element
    
    // fetch when needed - example use:
    input.addEventListener('input', () => { console.log(input.value) };
    

    I hope this clears it. If not comment below. else select as answer plz

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