Reputation: 11
Ok so I am trying to learn some basic javascript and html using a few different websites, when I got stuck. I have tried looking though this forum for another question like mine, but all the coding just goes right over my head and I don't understand a thing. I am trying to get the user to select a name from a drop down menu and then get that name to be printed in an alert along with a short message. This is what I have so far.
HTML
<select name="name">
<option value="Matthew">Matthew</option>
<option value="John">John</option>
<option value="Jared">Jared</option>
</select>
<input type="button" value="Submit" onclick="Message()" />
Javascript
function Message()
{
var name = document.getElementsByName(name).value;
alert("Hi " + name)
}
I know this is probably really simple, but I would appreciate it if you explained what I did wrong and provide a fixed version of the code.
Thanks in advance, Matthew
Upvotes: 1
Views: 37
Reputation: 759
you can use it in this way
<select id="name">
<option value="Matthew">Matthew</option>
<option value="John">John</option>
<option value="Jared">Jared</option>
</select>
<input type="button" value="Submit" onclick="Message()" />
and your javascript
function Message()
{
var name = document.getElementById('name').value;
alert("Hi " + name)
}
It will work fine.
Upvotes: 0
Reputation: 121998
You should write "name"
not simply name
.
It should be a string not variable
.
Change it to
var name = document.getElementsByName("name")[0].value;
And do not use reserved key words,They create mess some times.
Example :<select name="userName">
not simply <select name="name">
Upvotes: 0
Reputation: 27364
Replace
.getElementsByName(name).value;
with
.getElementsByName('name')[0].value;
-------------------^----^-----
you were missing '
.
Upvotes: 1