Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 823
Lukas Avatar asked Aug 08 '12 21:08

Lukas


4 Answers

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

demo

like image 80
Ricardo Alvaro Lohmann Avatar answered Oct 12 '22 09:10

Ricardo Alvaro Lohmann


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.

like image 29
Kevin B Avatar answered Oct 12 '22 09:10

Kevin B


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.

like image 35
Landan Jackson Avatar answered Oct 12 '22 10:10

Landan Jackson


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

like image 39
Raul Avatar answered Oct 12 '22 10:10

Raul