6

I am having a difficult time with keydown and stop propagation

i do not want my page to refresh, i have tried every which way i can think of, my current code is

 <script>
 $(document).ready(function() {
 var e = jQuery.event( 'keydown', { which: $.ui.keyCode.ENTER } );

 $('#id_number').trigger(e, function(event){
event.preventDefault();
event.stopPropagation();
});

 });
 </script>

any idea on what i am doing wrong here? I thought that the event was called correctly, i have jquery and jquery ui linked correctly and receive no console errors

UPDATE well it was working, now im getting Property 'event' of object function (a,b){return new e.fn.init(a,b,h)} is not a function error on the below code

 $(document).ready(function() {
 var e = jQuery.event( 'keydown', { which: $.ui.keyCode.ENTER } , function(event){
  event.preventDefault();
  event.stopPropagation();
}); 

 $('#id_number').trigger(e);

 });

UPDATE #2 - fixed

things I learned

  1. trigger() not needed in the document(ready)
  2. getting $.ui.keyCode to work was difficult (at least for me)
  3. always see what other functions are attached to the input (onblur, onfocus, ect) aka doh

rewrote it to this, works perfectly fine

 $(document).ready(function() {
    $('#id_number').keydown(OnKeyDown);
 });    

function OnKeyDown(e){
var code = (e.keyCode ? e.keyCode : e.which); //to support both methods
if(code == 13) { //the Enter keycode

    //my actions
 return false;
 }
}
Jay Rizzi
  • 4,196
  • 5
  • 42
  • 71
  • Why do you think that the `event` function (*which you must change to `Event` with capital E*) takes a 3rd argument ? according to docs it only takes two arguments.. first is event type and second is an object with event properties.. – Gabriele Petrioli Oct 04 '12 at 16:01
  • because I was thinking dumb? got confused, sorry bout that your answer was right i just couldnt get it to work until i rewrote the code – Jay Rizzi Oct 04 '12 at 19:03
  • @worthycaesar, something more in regards to your fix. jQuery normalizes the `event.which` so it always contains the key that was pressed.. see http://api.jquery.com/event.which/ – Gabriele Petrioli Oct 05 '12 at 00:58

1 Answers1

9

The code to stop the default action must go to the element that the event applies to..

$('#id_number').keydown(function(event){
  event.preventDefault();
  event.stopPropagation();
});

The .trigger() second argument is for extraParameters

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317