tags:

views:

2374

answers:

4

How do i send a trigger keypress of a particular keyCode eg. "9" event on a TextBox using JQuery programmatically?

This what i intend to do; Programmatically enter a value to a TextBox and then programmatically trigger a tabkey on the TextBox to exit the field.

my code

$("#tags1").val("comp") // Works well

$("#tags1").trigger("keypress",[9]); // Fails!!

Gath

+2  A: 

The jQuery documents state that it'll only pass normalized event attributes = the properties of the jQuery.Event object, which don't seem to include event-specific data.

I tried, and couldn't get it to insert text into a textbox even when reusing an event object that a browser keypress created, so it doesn't seem to be possible.

Why can't you just change the value of the textbox, and call blur() to exit it? (Or focus() on the one you want to enter next?)

Sii
A: 

Not exactly what you asked, but instead of using keypress this might accomplish what you want:

$("#tags1").blur();

or even

$("#tags1").next().focus();
system PAUSE
A: 

Try:

 $("#tags1").val("comp").trigger("keypress",[9]);

or

   $("#tags1").val("comp").trigger("keypress", [{
    preventDefault:function(){},
    keyCode:9
    }]);
TStamper
A: 

Try this:

$('textarea:input').live('keypress', function(e) {
 if (e.keyCode == 9) {
  e.preventDefault();

  // Press TAB to append a string (keeps the original TEXTAREA text).
  $(this).append("TAB TAB TAB AFTER TEXTAREA TEXT");

  // Press TAB to append a string (keeps the original TEXTAREA text).
  $(this).focus().prepend("TAB TAB TAB BEFORE TEXTAREA TEXT");

  // Press TAB to replace a all text inside TEXTAREA.
  $(this).val("INSERT INTO TEXTAREA / REPLACE EXISTING TEXT");

 }
});

If you want to add text inside the textarea (by the active cursor - like CTRL+V), you might want to use "Tabby" (JS source code) (jQuery plugin - 254 code lines..!).

You may also find inspiration in the YUI editor which will let you add TABs inside the editor.

Kristoffer Bohmann