user461316
user461316

Reputation: 913

Jquery KeyPress Doesn't work

Any idea why this doesn't work whatsoever on any browser?

If i try it in jsfiddle it works.

$('#input_area').keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

HTML

<script type="text/javascript" src="counts.js"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>

<body>
<input type="text" id="input_area"/>

</body>

JS

$(document).ready(function() {
$('#input_area').keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});
});

Upvotes: 1

Views: 8363

Answers (4)

Didin Ahmadi
Didin Ahmadi

Reputation: 491

Try to use binding,

$('#input_area').bind('keypress', function(e){
    alert(e.which);
});

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691695

If it works when running in jsfiddle, then it works. I suspect you're trying to register the keypress listener when the dom is not loaded yet, and input_area is not available yet. Wrap it inside $(document).ready :

$(document).ready(function() {
    $('#input_area').keypress(function(e) {
        if (e.which == 13) {
            alert('You pressed enter!');
        }
    });
});

Upvotes: 0

Nathan Anderson
Nathan Anderson

Reputation: 6878

Depending on the browser, the which property might not be implemented. You should also check for keyCode:

 $(document).ready(function() { 
    $("#input_area").keypress(function (e) {
       if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
         alert('You pressed enter!');
       }
    });
 });

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

I am ready to bet 5 bucks that you didn't wrap it in a document.ready handler in your actual application which jsfiddle does by default:

$(function() {
    $('#input_area').keypress(function(e) {
        if(e.which == 13) {
            alert('You pressed enter!');
        }
    });
});

Another possibility is you forgot to reference jQuery or you referenced it from a wrong url.

Upvotes: 4

Related Questions