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!');
}
});
});
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!');
}
});
});
Share
edited Jul 7, 2011 at 17:46
user461316
asked Jul 7, 2011 at 17:25
user461316user461316
9133 gold badges12 silver badges31 bronze badges
7
- Can you link us to the fiddle you used? – Abe Miessler Commented Jul 7, 2011 at 17:27
-
1
any error message? sample html? Are you binding the keypress on
$(document).ready()
? – Stuart Burrows Commented Jul 7, 2011 at 17:27 - Works: jsfiddle/simevidas/Mpcpd – Šime Vidas Commented Jul 7, 2011 at 17:29
- It works here in Firefox: jsfiddle/XRER3 If you got it to work in jsfiddle then it must be working in SOME browser. Where exactly is this not working? – Abe Miessler Commented Jul 7, 2011 at 17:29
- If it works in an isolated case on jsfiddle, the problem is surely with the markup or code context. We can't help you unless you post more code. – DarthJDG Commented Jul 7, 2011 at 17:30
4 Answers
Reset to default 4I 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.
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!');
}
});
});
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!');
}
});
});
Try to use binding,
$('#input_area').bind('keypress', function(e){
alert(e.which);
});