jQuery .val change doesn't change input value

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.


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

demo


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.


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.


$('#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.