1

I have a simple web-application with an input text field in it looking like this:

<input id="txtip" type="text" value="10.1.1.50" />

The address 10.1.1.50 is a default value for an ip address. And from javascript I would read it like this:

txtip.getAttribute("value")

Now let's suppose to change it to 10.1.1.49. In google chrome the above javascript code will still return 10.1.1.50, while the expression

txtip.value

returns 10.1.1.49.

What is the difference? What is the "right way"?

beddu
  • 71
  • 9
  • Can you reproduce issue at stacksnippets? – guest271314 Oct 17 '17 at 04:15
  • `value` is an attribute of `input` so that's why you can access it via `getAttribute` but `value` is also a property of node type `input`. I would use `txttip.value` – JohanP Oct 17 '17 at 04:23

1 Answers1

3

var el = document.getElementById('testBox');

$(document).focusout(function () { 
alert('el.value = ' + el.value);
    alert('el.getAttribute("value") = ' + el.getAttribute('value'));
    e.preventDefault();


});
<h2>Change value in the text box</h2>


<input id="testBox" type="text" value="original value" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Found this on web might help you try following code type something and focusout

The difference is that element.value is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.

While getAttribute('value') will still show the original value="whateverWasHere" value.

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
  • Not always, it's a mixed bag. See [*getAttribute() versus Element object properties?*](https://stackoverflow.com/questions/10280250/getattribute-versus-element-object-properties) The use of jQuery in your answer is unnecessary and detracts from what you're actually trying to show. – RobG Oct 17 '17 at 05:38
  • Thanks for the comment ! – Nisal Edu Oct 17 '17 at 05:39
  • thank you guys, now its clear – beddu Oct 19 '17 at 09:53