2

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Vincent Chua
  • 969
  • 6
  • 20
  • 41
  • 1
    possible duplicate of [Difference between Element.value and Element.getAttribute("value")](http://stackoverflow.com/questions/11973678/difference-between-element-value-and-element-getattributevalue) – Felix Kling Nov 29 '13 at 11:17
  • then use `$("#signUpEmail").keyup(function(){ var value = $(this).val(); alert(value); })` – awsumnik Nov 29 '13 at 11:27

4 Answers4

4

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.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
3
$(this).attr("value"); //can access only default value

For example,

<input type="text" id="signUpEmail" value="email"/>
$(this).attr("value"); //returns email

Instead use prop()

 $(this).prop("value"); //for getting dynamic values

For example:

<input type="text" id="signUpEmail" />
$(this).prop("value"); //returns whatever you press
$(this).attr("value"); //returns undefined
Praveen
  • 55,303
  • 33
  • 133
  • 164
2

You are fetching the value attribute, which represents the default value not the current value.

Use the val() method instead of attr().

$(this).val()
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

In jQuery to get text of input field use:

$(this).val();

and for labels:

$(this).text();
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110