Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Change a value of an input

Hello all, I need help figuring out how to change a value of an input using JavaScript.

I thought just using the .value= "" would do the trick, however, it made no change.

I used: document.querySelectorAll("input[name=inputName]").value = "test"; but the value didn't change.

Any suggestions?

1 Answer

leong shing chew
leong shing chew
5,618 Points

If you have the id of the element, you could :

var element = document.getElementById('element_id');
element.value = 'random_value';

or if you want to use querySelectorAll, assuming there is only one element that matches the query:

var elements = document.querySelectorAll("input[name=inputName]");
elements[0].value= 'test';

It doesn't work in your example because querySelectorAll return a nodeList rather than a single object that you are using it for.

Perfect.

Thanks Leong!