mr_app
mr_app

Reputation: 1312

jQuery fetch keypress event on chrome and IE

I have a problem, with fetching the event "keypress" on chrome and IE. On firefox it works well.

function bind_input_keypress ($this) {  
    $($this).bind('input', function() {
        $($this).css('width',$($this).val().length*5.5+20);
    })
    $($this).bind('keypress',function(e) {
        /*  delete last extra... */
        if( e.keyCode == '8' && $($this).val()=='' ) { $('#extras b').remove(); }

        /* arrow up */
        if( e.keyCode == '38' ) {
            console.log('38 pressed');
        }
        /* arrow down */

        if( e.keyCode == '40' ) {
            console.log('40 pressed');
            ad_curr     = $('.ad_selectbox .autocomplete ul li.active');

        }
    });
}
$('input').focus(function(){
    bind_input_keypress($(this));
})

Why is this not working on chrome and IE?

You can check it on jsfiddle too http://jsfiddle.net/a5M6S/2/

Upvotes: 1

Views: 841

Answers (2)

user3033246
user3033246

Reputation: 1

function validateInput(keyPressEvent) {
    if (navigator.appName == "Microsoft Internet Explorer")
        var enteredKey = keyPressEvent.keyCode;
    else if (navigator.appName == "Netscape")
        var enteredKey = keyPressEvent.charCode;
    var enteredChar = String.fromCharCode(enteredKey);
    var retValue = true;
    var optionNumber = document.forms[0].challengeQuestion.selectedIndex;
    try {
        switch (optionNumber) {
            case 0:
                window.alert("You must secure your information with a challenge question and answer!");
                document.forms[0].challengeQuestion.focus();
                break;
            case 1:
            case 2:
            case 3:
                if (!/\D/.test(enteredChar) && !/\W/.test(enteredChar))
                    throw "You can only enter letters into this field.";
                break;
            case 4:
            case 5:
                if (!/\d/.test(enteredChar) && !/\W/.test(enteredChar))
                    throw "You can only enter numbers into this field.";
                break;
        }
    }
    catch(inputError) {
        window.alert(inputError);
        retValue = false;
    }
    finally {
        return retValue;
    }
}

Upvotes: 0

ama2
ama2

Reputation: 2681

I think the problem is that the keypress event in Chrome is not fired for arrow keys, instead keydown and keyup is fired. I believe it to be the same for IE.

Upvotes: 5

Related Questions