简体   繁体   中英

make javascript preform an action based on input in drop down menus

I have been trying to make a little web page where you select two items from a drop down menu and press a button and it plays a sound, the sound varying based on what is selected in the drop down menu. Unfortunately I am having trouble with getting my JavaScript to interact with the button and then getting JavaScript to exert what is selected in the drop down.

Here are some snippets of my basic code:

HTML:

<head>
    <script src="src/EEEE.js"></script>
</head>
<body>
    <input type="image" id="button" value="submit" src="img/Button.png" onclick="handleClick()"/>
    <br>
    <select id="who">
        <option value="name1">Name 1</option>
        <option value="name2">Name 2</option>
        <option value="name3">Name 3</option>
    </select>
    <select id="what">
        <option value="op1">Option 1</option>
        <option value="op2">Option 2</option>
        <option value="op3">Option 3</option>
    </select>
</body>

JavaScript (in a folder called "src"):

function handleClick(){
    var w1 = document.getElementById("who").value;
    var name = who.options[who.selectedIndex].text;
    if(name == "name1"){
        /*do this*/
    }else if(name == "name2"){
        /*do that*/
    }
}

i have fixed your code, you can see the fixed demo Here

basically you should have used 'value' instead of 'text' and attaching event via javscript seems to work.

Using jquery makes it easy:

$('#button').click(function(){
    dd1Val = $('#who').val();
    dd2Val = $('#what').val();
    alert(dd1Val + "" + dd2Val);
})

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