0

I have two input fields i want to trigger keypress of one input field on keypress of another input field.

What i have tried is


$('#example').keypress(function(event) { 

   var press = jQuery.Event("keypress");
   var code = event.keyCode || event.which;
   press.which = code ;   
   $('#search').trigger(press);

});

both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • possible duplicate of [Trigger Keypress with jQuery](http://stackoverflow.com/questions/16122380/trigger-keypress-with-jquery) – Dave Child Feb 25 '14 at 11:47

3 Answers3

2

Guess it's like $.click()

$('#search').keypress();
Konstantin Krass
  • 8,626
  • 1
  • 18
  • 24
2

Try this :

JavaScript

$('#example').on('keypress keyup keydown',function(event) { 
  // create the event
   var press = jQuery.Event(event.type);
   var code = event.keyCode || event.which;
   press.which = code ;   
  // trigger 
  $('#search').val(this.value);
  $('#search').trigger(event.type, {'event': press});
});

// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) { 
   // sample  
   console.log(event.type);
});

Demo here : http://jsbin.com/pebac/1/edit

Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.

Tiberiu C.
  • 3,365
  • 1
  • 30
  • 38
-1

If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.

j.koch
  • 8
  • 3
  • 8