I'd like to pass the value of a text input into a switch statement when the user presses the enter button. I'd like to do this without using a button to submit. I have a short list of commands the user can enter into the text field, and the result of the switch statement simply logs to the console for now.

EDIT: I should also mention that I'm trying to build this using pure JS.

var cmdValue = document.getElementById('cmdLine').value;

switch(cmdValue){
    case "jump":
        console.log("FTL Jump to new system: SUCCESS");
        break;
    case "refuel":
        console.log("Refuel: SUCCESS");
        break;
    case "repair":
        console.log("Repair: SUCCESS");
    default:
        console.log("Command not recognized");
}

Here is the Fiddle

有帮助吗?

解决方案 3

You need to register a callback function, which will be invoked whenever a key in keyboard is pressed and your logic has to be in that function (or some other function and invoked from this callback function), like this

document.getElementById("cmdLine").addEventListener('keydown', function (event) {
    if (event.keyCode === 13) {
        var cmdValue = document.getElementById('cmdLine').value;

        switch (cmdValue) {
            case "jump":
                console.log("FTL Jump to new system: SUCCESS");
                break;
            case "refuel":
            case "repair":
                console.log("Refuel: SUCCESS");
                break;
            default:
                console.log("Command not recognized");
        }

    }
});

Updated jsfiddle

其他提示

In Jquery...

$(document).keypress(function(e) {
    if(e.which == 13) {
        //whatever
    }
});

JSFiddle

This is more or less what you want. You'll need to attach an event handler to the input and pass it a function containing your switch statement logic:

window.onload = function() {
  var cli = document.getElementById('cmdLine');

  // Add event listener on the 'keyup' event to execute the command
  cli.addEventListener('keyup', executeCommand);

  function executeCommand(e) {
    var cmdValue = cli.value;   // get the current value of the cli
    if (e.keyCode === 13) {     // if key equals 'enter'
      switch(cmdValue){
          case "jump":
              console.log("FTL Jump to new system: SUCCESS");
              break;
          case "refuel":
              console.log("Refuel: SUCCESS");
              break;
          case "repair":
              console.log("Repair: SUCCESS");
          default:
              console.log("Command not recognized");
      }
    }
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top