3

We're using some very simple jQuery to change the value of our text field:

<input type="text" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);

This changes the value displayed in the browser, does NOT however change the value attribute of our text field in the source code.

Now, consider this:

<input type="hidden" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);

Change the input type to hidden and the value attribute DOES change!

1.Does this mean we have to do the following to change our input field's value displayed in the browser AND its value attribute in the source code?:

<input type="text" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);
$('#sonderrabatt').attr('value',sonderrabatt);

2.Why does .val() work for type=hidden and NOT for type=text input fields?

Richard Tinkler
  • 1,635
  • 3
  • 21
  • 41
  • Why do you want to change the actual `value` attribute of the `text` field? – tymeJV Jul 09 '15 at 16:04
  • You could use $('#sonderrabatt').attr('value', 'newvalue'); but why would you want to do that? – Keammoort Jul 09 '15 at 16:06
  • the browser will keep track of the "real" value of the input, i am not sure if it will even fall back of the value attribute if a value is not present. I only use value attribute for input value initialization on page load – Ji_in_coding Jul 09 '15 at 16:07
  • The same and for data attribute, here in doc's you can find that: 'The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).' http://api.jquery.com/data/ – Sergiy Kozachenko Jul 09 '15 at 16:15
  • As per the documentation of jQuery `val()` should work absolutely fine. See here: http://api.jquery.com/val/ Have you written you script after the input html? – Imran Jul 09 '15 at 16:17

1 Answers1

11

.val() changes the elements property value, not attribute value. Attributes are what the html shows on initial render and properties contain the actual values in the DOM object which can be changed many times but may not be displayed in HTML after initial render.

.val(myValue) is shorthand for .prop('value', myValue)

In plain JavaScript

element.value = myValue; // set property on DOM object
element.setAttribute('value', myValue); // set attribute on HTML element

Just remember

  • DOM elements (HTML) -> attributes

  • DOM objects (JS) -> properties

Related

Community
  • 1
  • 1
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64