简体   繁体   中英

Drop down list and button not working

I have the HTML segment:

<select id="myList">
<option value="1"selected="selected">Position 1</option>
<option value="2">Position 2</option>
<option value="3">Position 3</option>
<option value="4">Position 4</option>
<option value="5">Position 5</option>
</select>
<input type="submit" id="go" value="Go to Position"></input>

Which prompts the user to select a position for a spotlight. The JS side contains this:

var select = document.getElementById("myList");
var answer = select.options[select.selectedIndex].value;

if (answer == "1") {
    document.getElementById("go").onclick = function () { ightAtX = -1.0; lightAtZ = 0.5; };
} else if (answer == "2") {
    document.getElementById("go").onclick = function () { lightAtX = -1.0; lightAtZ = -0.5; };
} else if (answer == "3") {
    document.getElementById("go").onclick = function () { lightAtX = 0.0; lightAtZ = -0.5; };
} else if (answer == "4") {
    document.getElementById("go").onclick = function () { lightAtX = 1.0; lightAtZ = -0.5; };
} else if (answer == "5") {
    document.getElementById("go").onclick = function () { lightAtX = 1.0; lightAtZ = 0.5; };
} else {
    return; 
}

I want the user to click the 'Go to Position' button in order to change the position of the spotlight. However, when I click the button, nothing changes. What am I missing?

You need to check the selection (answer) inside of the onclick function. The answer is evaluated once (unless there's more code not included), and wont be dynamically updated unless you tell it to.

Something like this:

document.getElementById("go").onclick = function () { 
    var select = document.getElementById("myList");
    var answer = select.options[select.selectedIndex].value;

   if (answer == "1") {
   }...
}

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