Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

$(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

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

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

$(this).val()

In jQuery to get text of input field use:

$(this).val();

and for labels:

$(this).text();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top