Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing value of `value` attribute for an `<input>` element

Tags:

html

jquery

Why can't .attr() change the value of value?

$("input").attr("value") = "New text";

See also a live jsfiddle example

like image 806
Randomblue Avatar asked Nov 28 '22 03:11

Randomblue


2 Answers

In general: Because the value attribute sets the default value, not the current value. Use the val() method instead.

$("input").val("New text");

In your specific case (because the value hasn't be changed by the user): because the attr method doesn't give you something you can assign a value to (and can't be written in such a way as would allow you to). It takes two arguments, the second of which is the value you want to assign.

$("input").attr("value", "New text");
like image 124
Quentin Avatar answered Nov 30 '22 16:11

Quentin


Replace $("input").attr("value") = "New text";

with $("input").attr("value","New text");

attr( attributeName, value )

That is the proper signature for attr

like image 44
Joe Avatar answered Nov 30 '22 16:11

Joe