Kate
Kate

Reputation: 1576

JavasScript textbox value not updated until focus is lost

I'm using Dojo for this but suspect this issue is native to JavaScript rather then dojo specific. I've created a text box and registered a function to be called when the onInput event is fired (I've tried this with onKeyPress, onKeyUp and onKeyDown, so essentially all the events that would be fired when the user enters text).

The event is fired so that is working great. The problem is that in the method I reference the textboxes value and it isn't getting updated. The textbox value is only updated if the textbox loses focus. When I then type in the box again I get the value as it was after losing focus, i.e. not including the additional keypress that fired the event. So, this is the code being called onInput:

console.log("searching for: " + this.textbox.value);

when I type "tes" into the (initially empty) text box, I'get three lines in the console log as follows:

LOG: searching for:
LOG: searching for:
LOG: searching for:

If I then click elsewhere on the page, then back into the textbox and type again, say a 't', I get:

LOG: searching for: tes

If I click away again then back and type, say "1", I get:

LOG: searching for: test

I'm sure I've made a silly mistake somewhere. Can anyone tell me how to get the current content of the textbox immediate after a keypress type event being fired, rather than the value prior to the last loss of focus?

Thanks Simon

edit:
As requested, here is the code (from my SearchUtils.js class), including settings the intermediateChanges property to true which solved the problem incase it helps anyone else to refer to it.

    // Create the Search UI
    createUI: function (elementName) {

        // Get a reference to attach the UI to
        var element = dojo.byId(elementName);
        if (element) {

            // Add a text box to enter the search text
            this.textbox = new dijit.form.TextBox({
                id: "txtSearch",
                intermediateChanges: true
            });
            this.textbox.on("change", lang.hitch(this, this.search));
            this.textbox.placeAt(element);

        }

    }

Upvotes: 0

Views: 819

Answers (1)

Craig Swing
Craig Swing

Reputation: 8162

If you use a dijit/form/TextBox, you can set the intermediateChanges property to true. This will update the value of the widget using the onKeyPress event and not the onBlur event.

Upvotes: 2

Related Questions