0

My problem is that in JavaScript, when requesting input field to which I have written e.g "abc":

input_obj // <input type="text" value="">
input_obj.getAttribute("value")  // returns: ""
input_obj.value                  // returns: "abc"

I want to get user input with getAttribute() but it does not update on the contrary to .value property. First one returns what's in the original HTML and the other what's currently on the screen.

Anyone knows how to get user input but with the use of attribute name in string?

Poij
  • 27
  • 4
  • Does this answer your question? [When to use setAttribute vs .attribute= in JavaScript?](https://stackoverflow.com/questions/3919291/when-to-use-setattribute-vs-attribute-in-javascript) – Hemera Jul 30 '21 at 08:25
  • Only after reading the answers did I understand what you probably mean by _“but with the use of attribute name in string”_. Please [see](//google.com/search?q=site%3Astackoverflow.com+js+get+property+by+string) [Dynamically access object property using variable](/q/4244896/4642212). – Sebastian Simon Jul 30 '21 at 08:34

1 Answers1

1

The value attribute represents the initial value of the input.

The value property represents the current value of the input.

They are distinctly different things, even if they share a name.

There is no attribute that represents the current value.

You cannot use getAttribute to get the current value.


To read a property using a string variable containing the name, use square bracket notation.

input_obj["value"]
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335