Ewan Ewan - 3 months ago 11
Javascript Question

JavaScript always check the input

I'm going to start off with an apology, I am totally new to this, so excuse my ignorance.

I can't manage to find a simple example of how to check html input with JavaScript.

I'm building a search function and I don't know how to get my code to check what a user input and to always be checking what they say. Not fire a set number of times.

ie.

User types "a" into an

<input>
.

User input is set to a variable and will constantly update.

In this case
var userInput = 'a'
.

I suppose another way to phrase it is I want
document.getElementById('userInput')
but to get it constantly.

I hope I was clear!

Answer

Let's say you have an HTML text input like this:

<input id="userInput" type="text">

To listen for when a key is pressed in that textfield:

var userInput = document.getElementById('userInput');
userInput.onkeyup = function() {
  console.log(this.value);
};

Or, with jQuery:

$("#userInput").keyup(function() {
  console.log($(this).val());
});