7

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

6 Answers 6

6

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?)

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

or even

$("#tags1").next().focus(); 

Comments

1

Try:

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

or

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

Comments

1

I created a simple jQuery plugin which does solve this problem. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.

Example usage:

// Simulate tab key $.tabNext(); 

Comments

0

If you wan to add a value to an input / textarea then fire the keypress "enter" event.

Trigger it like this

$('input').val( input_value ).blur(); 

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.