I can’t get any key events to fire on an input element with jquery. Given the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="./js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="./js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript">
$("#cmd").keypress(function(event) {
alert("keypress");
if(event.which == 13){
$.ajax({
type: "POST",
url: "update",
data: "key=" + key + "&cmd=" + $("#cmd").val()
});
$("#cmd").val("");
$("#cmd").focus();
}
});
</script>
<title>BCMD</title>
</head>
<body>
<div id="main" style="background-color: black; color: white; width:100%; height:500px;">
<input id="cmd" type="text" style="border:0;"></input>
</div>
</body>
</html>
Nothing is firing. Any ideas? Thanks.
You’re missing the $(document).ready function. Enscapsulate your Javascript in $(function() {} ); to get it to work.
JQuery requires this kind of code to be encapsulated like that to indicate it should only be run when the document has loaded.