I have this code:
$(document).keyup( function(e) {
console.log($(this).attr('id'));
});
When typing in an HTML input tag with an id, the output in console.log is:
undefined
How then to use $(this) within the keyup function?
The event object has a target
property which can be used for this:
$(document).keyup( function(e) {
console.log($(e.target).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" id="foo">
You could even take it a step further and migrate away from .keyup()
and instead standardize on .on()
, which can be more clear about event delegation. For example:
$(document).on('keyup', 'input', function(e) {
console.log($(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" id="foo">
In the above case the second argument to .on()
is a selector to be used at runtime to determine if the originating element should trigger the event handler, and within the event handler this
refers to that originating element.