简体   繁体   中英

Selections and Alerts

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

Replace

.getElementsByName(name).value;

with

.getElementsByName('name')[0].value;
-------------------^----^-----

you were missing ' .

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">

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM