0

I'm working on a text adventure at the moment that has a text input form at the bottom that will take the player's commands, such as "Go North" or "Get item". Previously, i had to have a button beside it that would activate a function to parse whatever string value the form held and interpret it, but i'd realy like to be able to just hit the "Enter" key to start that function.

Problem is, whenever i hit the enter key in the form, the page refreshes and it attempts to submit the form, even though i simply want it to activate a function.

i've tried something like

$("userInput").keydown(function(event) {
        if (event.keyCode == 13) {
            inputHandler()
            event.preventDefault();
        }       
    });
});

Where "userInput" is the id of the form that the player types command in, but that didn't seem to work, the page keeps refreshing when i hit Enter.

I don't quite understand what i'm doing wrong, bear in mind i'm new-ish to Javascript/jQuery so it may just be lack of experiance.

  • Is it because the form is submitting? Does this help http://stackoverflow.com/questions/895171/prevent-users-from-submitting-form-by-hitting-enter – mbrrw Apr 05 '14 at 19:29
  • It looks like that's why its not working, but i found that question earlier and tried that solution and it didn't seem to work. – user3501663 Apr 05 '14 at 19:32

2 Answers2

2

you forgot to include the # (should be $('#userInput') ). I think this is what you're looking for

$('#userInput').keypress(function(event) {
  if (event.which == 13) {
    alert("run function here");
    event.preventDefault();
  }
});

JSFIDDLE

jmore009
  • 12,863
  • 1
  • 19
  • 34
0

Simply change:

$("userInput").keydown(function(event) {
        if (event.keyCode == 13) {
            inputHandler();
            event.preventDefault();
        }       
    });
});

To:

$("userInput").keydown(function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            inputHandler();
        }       
    });
});

So you firstly run event.preventDefault and then the function. Also remember to add a "#" if you are selecting an element by it's ID or a "." if you are selecting an element by it's CLASS.

e---
  • 40
  • 8
  • Thank you so much, i ended up doing this and changing .keydown to .submit and removed the if statement, and it ended up working fine. Thanks for your help :D – user3501663 Apr 05 '14 at 19:39