user3501663
user3501663

Reputation: 3

How to prevent enter key in a from from refreshing page?

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.

Upvotes: 0

Views: 233

Answers (2)

jmore009
jmore009

Reputation: 12923

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

Upvotes: 2

e---
e---

Reputation: 40

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.

Upvotes: 0

Related Questions