Reputation: 3210
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>
Upvotes: 1
Views: 78
Reputation: 25796
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.
Upvotes: 1
Reputation: 16150
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.
Upvotes: 1
Reputation: 39902
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>
Upvotes: 1
Reputation: 82337
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">
Upvotes: 0