简体   繁体   中英

How to click a textarea and then press the spacebar using jquery

I am trying to click into a textarea using jquery and then press the spacebar. So far I've got the click aspect, easy enough: $( "textarea" ).click() , but how can I now press spacebar?

Note: should be spacebar because of additional functionality linked to spacebar event press.

The spacebar inserts a ..... wait for it ....... space, so why not just add a space to the value

$( "textarea" ).val(function(_, val) { return val + ' '; }).focus();

Also, clicking a textarea .... wait for it .... focuses the textarea, and there's an event for that.

There are also ways to trigger events manually, but you have to know what event to trigger

var e = $.Event("keyup", { which: 32 });

$("textarea").trigger( e );

jQuery allows creation of an event, as shown in their documentation which you can then pass to the trigger function to fire it.

$("textarea").trigger($.Event("keydown", {
    which: 32
}));

You may need to fire an appropriate keyup and/or keypress depending on the events being listened for by the handlers you want to trigger.

Got it, thanks for the input:

$( "textarea" ).trigger({type: 'keypress', which: 32, keyCode: 32});
$('textarea').focus()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM