e.target.value shows values one key ‘behind’

Input type with id ‘typehere’. There is a keydown event set on typhere. The simple problem is that e.srcElement.value seems to have a value one key behind. i.e. if the value should ‘s’ , its consoled’logged as blank ” . If I type ‘ss’ , the value shown is ‘s’ . I can’t seem to figure this one out.

console.log(e), shows the correct value of e.srcElement.value (in the console), but console.log(e.srcElement.value) shows the wrong value. Why?

<script type="text/javascript">
            var xmlHttp = createXmlHttpRequestObject();
            selectOption = document.getElementById('choose_colony') ;

            document.body.onload = function () {
                typehere = document.getElementById('typehere') ;

                addAnEvent(typehere,"keydown",handleKeyDownevent,false )  ;

            function handleKeyDownevent (e) {
                e = e || window.event ;
                if (xmlHttp) {
                    try {
                        //xmlHttp.open('GET' , 'async.txt', true ) ;
                           console.log(e.srcElement.value ) ;
                       var target=  e.target || e.srcElement ;
                        var typed = target.value      ;
                        if (typed != ""){
                            console.log('sennding request') ;
                            //ajax request
                        else {
                            console.log(e.srcElement.value + "is blank") ;
                    catch(e) {
                        console.log('could not connect to server') ;


The script tag are before the </body> tag btw


(For typeable characters, you typically want keypress rather than keydown as keypress repeats.)

keydown is fired before the value has changed (as does keypress), not least so you can cancel the keypress, so if you want to process the value after it’s changed, you may want to defer your call using setTimeout(func, 0). Your call will get processed after the event chain unwinds. (Typically within 5-10 milliseconds.)

Live example

So in your code, that might look like this:

addAnEvent(typehere,"keydown",function(e) { // or "keypress"
    e = e || window.event;
    setTimeout(function() {
    }, 0);
},false )  ;

Leave a Reply

Your email address will not be published. Required fields are marked *