31

I have a

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

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

0

4 Answers 4

70

The simple easy way is:

$("#text").val ("foo");
Sign up to request clarification or add additional context in comments.

Comments

22

It's as easy as this:

$("#text").attr("value", "some value");

6 Comments

What did I get downvoted for? My answer is correct, even if it isn't the absolute shortest way to do it.
dunno, and asker should be aware that your solution can be used for any attributes
not sure however .val is quicker and preferred route than the attr.
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.
@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
|
13

The Javascript would be:

document.getElementById('text').value = 'Blahblah';

Comments

9

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.