1

I'm trying to get the text from a textbox as a user types, so that I can parse it and display information accordingly as the user enters a command. However, it seems as though the function I'm writing is getting the text from the box before the letter is entered into the text box. How do I prevent the function from grabbing the content from the textbox before the typed character is entered? I considered grabbing the id of the key and altering the inputted string accordingly, but I feel like there should be a better way.

The code:

$('#inputConsoleForm').keydown(function(event){
    //Get key code
    var code = (event.keyCode ? event.keyCode : event.which);
    //Get console text (doesn't behave as expected)
    var consoleCommand = document.inputConsoleForm.console.value;

    function parseConsoleCommand(consoleCommand) {
        /* Returns true if command is valid*/
    }
    if(code === 13) {
        event.preventDefault();
        if(!parseConsoleCommand(consoleCommand))
            alert("INVALID COMMAND LINE");
        else
            attemptExecute();//Runs the command
    }
    if(code === 32 || (code >= 48 && code <= 123) || code === 61 || code === 109 || code === 188 || code === 8) {
        if(parseConsoleCommand(consoleCommand)){
            $(document.inputConsoleForm.console).css("background-color", "#FFDFDF");
        }
        else{
            $(document.inputConsoleForm.console).css("background-color", "");
        }
    }
});
Salem
  • 1,122
  • 4
  • 19
  • 30

2 Answers2

2

You could use the HTML5 input event (falling back to the propertychange event in IE < 9). Here are two answers detailing how to do this:

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

Use "change" for best results I'd say. You could continue to use keydown (or keyup) but you'll have to fetch the key being pressed from the event object and append it to the text string.

Primus202
  • 648
  • 7
  • 24
  • 1
    If he used keyup (or keypress) he wouldn't have to fetch the key being pressed. – Kevin B Jun 20 '12 at 21:16
  • 1
    Change won't fire on an input type=text until the user leaves it. – Martijn Jun 20 '12 at 21:17
  • Really? I thought change fired whenever there was a change of state for an input, including the text. Never mind. You are correct sir: `For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.` – Primus202 Jun 21 '12 at 14:35