02 June 2013

Value Attributes Don't Always Mean What You Think They Mean

I recently discovered the hard way that the "value" attributes of different HTML elements can have subtle and frustratingly different meanings.

Take a look at this simple example:
<input type="button" value="one" id="buttonX">
<input type="text" value="one" id="textX">

<script>
  var buttonX = document.getElementById("buttonX");
  var textX = document.getElementById("textX");

  buttonX.value = "two";
  textX.value = "two";

  buttonX.setAttribute("value","three");
  textX.setAttribute("value","three");
</script>
(View this as a JSFiddle: http://jsfiddle.net/sEpMz/)

After running this code, you would probably guess that the text visible in the two widgets would both be "three", but in fact, the button will display "three" while the text box will display "two"!

The reason behind this is that for certain input element types, the "value" attribute defines the initial text of the widget, while for other element types, the "value" attribute defines the visible text of the widget!

The important distinction here is between the "value" attribute (the value="something" that appears in the HTML), and the "value" property (elementX.value = 'something' in JavaScript). The property will always reflect what is displayed in the widget on the page, while the attribute has different behavior depending on the type of the input element.

No comments: