Reputation: 725
Let's say I have an input field with an id of code ( #code ).
How can I tell when a new character has been typed in it with javascript or jQuery ?
This is when the text is manually being entered or is done by javascript / jQuery.
Upvotes: 3
Views: 4740
Reputation: 151
This will trigger on every keypress.
Using Javascript:
document.getElementById('id').addEventListener('input',function(e){
console.log("Print Hello World");
//do something else
});
Upvotes: 2
Reputation: 5879
Edit
In modern browsers only, you can use the "input" event. The change event will probably help you in most cases for all browsers and jQuery and JS examples are defined below. As mentioned the change event will only fire on an input losing focus so you'd have to use a combination of techniques to cover all bases, including checking the field value at given intervals. A thorough explanation that covers all scenarios can be found on SO here: Detecting input change in jQuery?
jQuery:
$('#code').on('change', function(e){
//do something
});
Javascript
document.getElementById('code').addEventListener('change', function(e){
//do something
});
Upvotes: 1
Reputation: 123739
Use Change function to track any changes in the textbox input. Change event will be triggered only if you focus out of the text box
$('#idoftextbox').change(function(){
//do something
});
If you want to detect as the user enters something then you need to use KeyPress
$('#idoftextbox').keypress(function(event) {
if ( event.which == 13 ) { //This will give you the key code
event.preventDefault();
}
});
Upvotes: 2