126

I have an HTML input with a link in the value.

<input type = 'text' value = 'http://www.link.com' id = 'link' />

I am using jQuery to change the value on a certain event.

$('#link').val('new value');

The above code changes the value of the text box but doesn't change the value in the code (value = 'http://www.link.com' stays unchanged). I need the value = '' to change as well.

Lukas
  • 1,824
  • 2
  • 20
  • 21
  • What do you mean by `in the code`? Are you looking at the original (thus, unmodified) source of the page? – Frédéric Hamidi Aug 08 '12 at 21:51
  • Using Chrome's inspect element. – Lukas Aug 08 '12 at 21:53
  • 3
    @Luke The value will change, but the HTML element's visible value in Chrome's inspector will not. Try then alerting the value or outputting it to the console and you'll see it has changed. See, it has changed: http://jsfiddle.net/a8SxF/ – TheZ Aug 08 '12 at 21:54
  • Yes I see that now. I'm using zClip to copy the value to the clipboard but it's copying the old value after it has changed. I think I can fix it with a little messing around. – Lukas Aug 08 '12 at 21:56
  • 1
    possible duplicate of [html() method wrong when input value has changed](http://stackoverflow.com/questions/11853666/html-method-wrong-when-input-value-has-changed) – Esailija Aug 08 '12 at 21:56
  • Changing the internal state of a form element is not reflected in the source code. – Felix Kling Aug 08 '12 at 22:14
  • Check my answer here: https://stackoverflow.com/a/60378508/2734348 – Anand Singh Feb 24 '20 at 14:57

9 Answers9

232

Use attr instead.
$('#link').attr('value', 'new value');

demo

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
  • 7
    This is totally correct, by using `setAttribute` or jQuery's `attr` you will also affect the DOM element's value: http://jsfiddle.net/a8SxF/1/ – TheZ Aug 08 '12 at 21:58
  • 4
    @TheZ that's because the input's dirty value flag is false. Try interacting with the input (the value is dirty after user input) and then setAttribute – Esailija Aug 08 '12 at 21:58
  • @Esailija Wow, that explains a lot. Just when I thought there couldn't be any more types of gotchas xD – TheZ Aug 08 '12 at 22:04
  • 6
    But when you want to get html with `.html()`, then there will be still the same old value, doesnt matter, if you use `.val('new value')` or `attr('value', 'new value')`... :( – Legionar May 27 '14 at 11:58
  • 1
    @Legionar : Upvoted by mistake. I see that the value in html() gets updated after using attr() – user Sep 18 '14 at 08:49
  • 7
    Coded a massive and complicated bunch of functions using .val (as suggested by everything I read previously) and had this exact same problem. Bloody annoying! This answer should be the first point of call for any jQuery newbies looking to update form elements dynamically. Would have saved me a good few hours if I'd read this first! – Grant Feb 04 '16 at 23:51
  • 4
    This is why it's so hard to hit the ground running with JavaScript/JQuery, so many caveats like this. This helped me a lot. Thank you! – eaglei22 Apr 13 '16 at 20:29
  • Just in case myself from a parallel universe reads this: if you're not bothering with trying `$('textarea')` (or getting it with `#id`) or any other "direct" method because you _do_ have a "seemingly perfectly valid" jQuery object that you obtained via another roundabout way (eg `$parentElement.children('textarea').first()`) I tell you: stop wasting time and find the object as directly as possible, sometimes `.val('')` will update the value in memory but not in the DOM, don't try to find an alternative, just do this. – Sebastián Vansteenkiste Oct 18 '18 at 19:54
  • What about a "select" element? – Anand Singh Feb 24 '20 at 13:41
  • This answer has me questioning the nature of my reality. I've been writing jQuery for years and never had any problem with `$("#hostName").val("Delores Abernathy");` but today I landed here as I have a form in which a hidden control (`display: none`, not ``) has its value set by jQuery using `.val()` and it triggers a "required field" validation error on form submission, even though `alert($("#hostName").val());` displays the expected value. I've never encountered this before, `.val()` always just works as expected. Have I just been incredibly lucky?! – Philip Stratford Nov 12 '20 at 12:00
  • Further to my previous comment, turns out that `.val()` still wasn't letting me down. The input was being disabled elsewhere in the code prior to form submission so the value wasn't being included in the submitted data. – Philip Stratford Nov 12 '20 at 12:16
19

Changing the value property does not change the defaultValue. In the code (retrieved with .html() or innerHTML) the value attribute will contain the defaultValue, not the value property.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 1
    That explains it. Typing also doesn't change the but does affect the result of $("#a").val(). A question just to be sure: Is $("#a").val(value) really the correct way how to change the value of an input element, so that the right value will be submitted? – Daniel Katz Sep 29 '14 at 10:11
  • 2
    Yes, that is correct. changing the attribute will not change what is being submitted. – Kevin B Sep 29 '14 at 14:41
8

to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426

http://api.jquery.com/val/#val2

about val()

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

Community
  • 1
  • 1
2

This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.

amira
  • 21
  • 8
2

For me the problem was that changing the value for this field didn`t work:

$('#cardNumber').val(maskNumber);

None of the solutions above worked for me so I investigated further and found:

According to DOM Level 2 Event Specification: The change event occurs when a control loses the input focus and its value has been modified since gaining focus. That means that change event is designed to fire on change by user interaction. Programmatic changes do not cause this event to be fired.

The solution was to add the trigger function and cause it to trigger change event like this:

$('#cardNumber').val(maskNumber).trigger('change');
dorado
  • 1,515
  • 1
  • 15
  • 38
2
$('#link').prop('value', 'new value');

Explanation: Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.

Raul
  • 963
  • 2
  • 11
  • 31
-1

My similar issue was caused by having special characters (e.g. periods) in the selector.

The fix was to escape the special characters:

$("#dots\\.er\\.bad").val("mmmk");
WiredIn
  • 4,157
  • 4
  • 27
  • 23
  • 1
    Agreed, very bad, you shouldn't escape, you should rename your element's id. – webaholik Jul 26 '19 at 03:02
  • Dots are valid selectors though if you're referring to a class ('.class-name'), but having a dot nested inside a name is a bad idea as that will attempt to find additional classes/id's. E.g $('.div.name') will look for a div which has both .div and .name as classes – Andrew West May 26 '22 at 12:45
-1

Note that the browser parses the HTML tag element and creates a corresponding DOM node object.

  • "Initial/starting/default value" of input:
    • Equals:
      • ONLY the initial value of value attribute of input's HTML tag element.
      • defaultValue property of input's DOM node object.
    • Is set in jQuery via:
      • $(input).attr("value", "42")
  • "Current value" of input:
    • Equals:
      • value attribute of input's HTML tag element
      • value property of input's DOM node object.
    • Is set in jQuery via:
      • $(input).val("42")
      • $(input).prop("value", "42")

See also: What is the difference between properties and attributes in HTML?

user2340939
  • 1,791
  • 2
  • 17
  • 44
-2
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>
ikerya
  • 129
  • 7
  • 2
    Yeah this doesn't update the actual value though. It updates the on screen text box, but when you try to submit a form the value is whatever it was when the page was originally loaded. – Grant Feb 04 '16 at 23:53