How to check contents of input in "real time"

You can use the input event to get changes when the user is typing inside of the field. On the change event you will be given the element corresponding to the input element the event listener is attached to as event.target. Using this reference you are able to get the value of the input by using the value property on the element.

After you have retrieved the value you will need to verify that it is in fact numerical. Thankfully jQuery provides a method called isNumeric that allows us to do just that.

Once we've established the fact that the value is indeed numerical you can either apply a class or just set the style to what you want to be. Make sure you also check if the value has been emptied so the user does not get confused.

As for the validation message - it's not a good idea to set the value of the input as the user is interacting with said element. Instead I've chosen to add textual element to represent the message that will be shown conditionally based on the validation state.

// Add error message element after input.
$('#some-number').after('<span class="error-message">Please enter numbers only!</span>')

$('#some-number').on('input', function (evt) {
  var value = evt.target.value
  
  if (value.length === 0) {
    evt.target.className = ''
    return
  }

  if ($.isNumeric(value)) {
    evt.target.className = 'valid'
  } else {
    evt.target.className = 'invalid'
  }
})
input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
  border: 1px solid black;
}

input.valid {
  border: 1px solid green;
}

input.invalid {
  border: 1px solid red;
}

input.invalid + .error-message {
  display: initial;
}

.error-message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="some-number">


You could bind your validation logic to a keypress event like

$('#target').keydown(function () {
    // validation
});

or

$("#target").blur(function() {
    // validation
});

Example:

https://jsfiddle.net/smzob72e/


You can do this with the onkeypress Event. Every time the user presses a key while the input box is selected, update the input's value.

Example:

var input = document.getElementById("input-box");
var inputValue = document.getElementById("input-box").value;

input.addEventListener("keypress", function() {
  inputValue = document.getElementById("input-box").value;
  // do something with it
});
<input id="input-box"/>

I hope I didn't get anything wrong.