I have an input
field that will cache its value
attribute. Example:
$("#signUpEmail").keyup(function(e) {
console.log(e.target.value); // Works
console.log($(this).attr("value")); // Doesn’t work
});
If I log them both in the console, e.target.value
will return my input
field, but not $(this).attr("value")
. Can anyone explain why that is?
Can explain why is that so?
e.target.value
accesses the DOM property, which always represents the current value of the input field.
On the other hand, $(this).attr("value")
accesses the HTML attribute, which is the value of the input as specified in the HTML markup. It doesn't update when the value is changed by the user.
You could use $(this).prop('value')
to access the property via jQuery, but as already mentioned, .val
is the usual way to do this.