views:

666

answers:

4

I have a

<input type='text' id='text' value='' />

How do I programmatically set the value attrribute using JQuery/Javascript

+3  A: 

It's as easy as this:

$("#text").attr("value", "some value");
Max Schmeling
What did I get downvoted for? My answer is correct, even if it isn't the absolute shortest way to do it.
Max Schmeling
dunno, and asker should be aware that your solution can be used for any attributes
David Archer
not sure however .val is quicker and preferred route than the attr.
redsquare
Yeah, I understand that. I just didn't know it existed (so I learned something). I just think it's kind of dumb for someone to downvote an answer that is correct.
Max Schmeling
Agreed. Upvoted for good measure. :-)
B.R.
ditto .
redsquare
@redsquare('.yourFirstComment') I agree completely that val() should be (is) the preferred route (no magic strings etc). I thought it is interesting enough to point out to the asker who probably is quite new to jquery
David Archer
I didn't up or down vote your response, but its good to know that this works for every attribute
AJM
+6  A: 

The simple easy way is:

$("#text").val ("foo");
B.R.
+1  A: 

The Javascript would be:

document.getElementById('text').value = 'Blahblah';
karim79
+2  A: 

In jQuery, you'd do it like this:

$("#text").val("my new value");

You might also want to read the jQuery documentation on this topic

Without jQuery:

document.getElementById("text").setAttribute("value", "my new value");

Hope that helps.

Rob Knight