tags:

views:

36

answers:

2

Trying to get jQuery to detect enter input, but space and other keys are detected, enter isn't detected. What's wrong below:


<script>
$("#entersomething").keyup(function(e){alert("up");
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code==13)e.preventDefault();
    if(code==32||code==13||code==188||code==186){
        $("#displaysomething").html($(this).val());
    });
</script>
<input id="entersomething" />
<div id="displaysomething"></div>
​

http://jsfiddle.net/zeRrv/

+1  A: 

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if(code==13)e.preventDefault();
    if(code==32||code==13||code==188||code==186){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>
Russ Cam
doh!! btw is there an IDE you'd recommend that can check for braces? tried using aptana, but having difficulty adapt to it and it doesn't have a shortcut for in-ide preview!
ina
Notepad++ FTW :) -http://notepad-plus-plus.org/
Russ Cam
If you are on OSX then Textmate wins hands down for me. Zend Studio and Aptana were nice and I'm sure that you can manually add shortcuts/hotkeys to do what you'd like???Interesting about `event.which`, never knew that before:https://developer.mozilla.org/en/DOM/event.charCode#Notes
balupton
@balupton - I should add that `event.which` is normalized in jQuery, in the `jQuery.event.fix` function
Russ Cam
+1  A: 

jQuery Sparkle includes a custom event for this. The source can be seen here: http://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.events.js

Here is a demo http://www.balupton.com/sandbox/jquery-sparkle/demo/#event-enter

balupton
neat plugin!! !
ina