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?

5
  • Why do you want to change the actual value attribute of the text field? Commented Jul 9, 2015 at 16:04
  • You could use $('#sonderrabatt').attr('value', 'newvalue'); but why would you want to do that? Commented Jul 9, 2015 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 Commented Jul 9, 2015 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).' api.jquery.com/data Commented Jul 9, 2015 at 16:15
  • As per the documentation of jQuery val() should work absolutely fine. See here: api.jquery.com/val Have you written you script after the input html? Commented Jul 9, 2015 at 16:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.