Hi All,

Relatively new to JS, but something strange is happening.

I have one function:

var commentContent = $('textarea.comment-box#comment');

commentContent.keydown(function(e){
    if((e.keyCode || e.which) == 13 && !e.shiftKey && commentContent.is(":focus"))
    {
        e.preventDefault();
        commentForm.submit();
    }
});

Which works absolutely fine. If the object is focused and I press Enter, the submit function is called.

Going down the line, a completely unrelated function:

var loadComments = $('.btn#load');

loadComments.click(function(e){

    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: '/comments/load',
            data: {'listing_id': listingID, 'comment': comment},
            dataType: 'JSON'
        });
    });

When I press this button, Chrome sends me this error: Uncaught TypeError: Cannot read property 'keyCode' of undefined and references the line if((e.keyCode || e.which) == 13 && !e.shiftKey && commentContent.is(":focus"))

I can't think why/how my second function would be firing the keydown event? Any ideas?

Try:

var commentContent = $('textarea.comment-box#comment');
commentContent.keydown(function(e){

    /* see: http://www.quirksmode.org/js/events_properties.html */
    var code;
    if (!e){
        var e = window.event;
    }

    if (e.keyCode){
        code = e.keyCode;
    }
    else if (e.which){
        code = e.which;
    }

    if( code == 13 && !e.shiftKey && commentContent.is(":focus"))
    {
        e.preventDefault();
        commentForm.submit();
    }
});
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.