문제

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.

다른 팁

$(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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top