1

Here is my code looks like, I would like to be able to use whatever user inputs as the value for my showColor function. I used document.getElementsByName, but I got some errors Type error. Can somebody help? Thanks!

<input type="text" name="color" value="Input Your Fav Color">
<button type="button" onClick="showColor('red')">Show Color</button>

4 Answers 4

1

I'm guessing it's because you're doing this

document.getElementsByName('color').value

You should be doing this instead

document.getElementsByName('test')[0].value

Because getElementsByName returns a collection, or alternatively give the element an id and use getElementById instead.

Sign up to request clarification or add additional context in comments.

Comments

1

You will want to assign an id to the target input so that you can easily retrieve its value via javascript.

<input id="userColor" type="text" name="color" value="Input Your Fav Color" >

You can then retrieve the value like so:

var usercolor = document.getElementById('userColor').value;

Or using your example

<button type="button" onClick="showColor(document.getElementById('userColor').value)">Show Color</button>

Comments

1

Use DOM:

<button type="button" onClick="showColor(document.getElementsByName('color')[0].value)">Show Color</button>

There will be problem if you have more elements with name color on the page, but I assume you haven't.

2 Comments

So you meant that getElementsByName would return an array of values of the same name?@Lolo
It's actually NodeList, but yes, it's collection.
0

You actually need to be using .getElementById("color") and have the input be

<input type="text" name="color" id="color" value="Input Your Fav Color">

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.