0

how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work

Heres the code

 <form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)"> 



</form> 
    <div id="canvasDiv" width="500" height="10"></div>
    <script type="text/javascript" src="robotti.js"></script>
    <script type="text/javascript">
        prepareCanvas(document.getElementById("canvasDiv"), 500, 500);

        document.getElementById("canvasDiv").onmousedown = function() { 
            jump(); }

            //document.getElementById("canvasDiv").onkeypress = function() { 
            //move(); }

            document.getElementById("canvasDiv").window.onkeypress = function(event) {
   if (event.keyCode == 41) {
      move();
   }
}
    </script>

3 Answers3

0

This should work -:

var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
    jump();
    getElementById("canvasDiv").value = "";
}
Abhisar Tripathi
  • 1,569
  • 10
  • 21
0

Please use onkeyup instead of onkeydown

<!DOCTYPE html>
<html>
<body>



<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">


<script>
function keyCode(e) {
 var text = (document.getElementById("canvasDiv").value).toLowerCase();
 if(text  == 'jump' || text == 'move'){
  //call jump function here
    alert("jump");
 }
 
}
</script>

</body>
</html>
PrateikG
  • 53
  • 1
  • 6
0

You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.

document.querySelector('input[type="text"]').addEventListener('keyup', function() {
  switch (this.value) {
    case 'move':
      console.log('move!'); // Your actual function here
      this.value = ''; // Reset value
      break;
    case 'jump':
      console.log('jump!'); // Your actual function here
      this.value = '' // Reset value
      break;
  }
});
Command the robot!: <input type="text" size="50">

Further reading:

Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector

CodeF0x
  • 2,624
  • 6
  • 17
  • 28