Reputation: 1643
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?
Upvotes: 3
Views: 4414
Reputation: 20633
.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
Upvotes: 11