Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically input text with JavaScript events

I'm trying to update the values of a text input with a close accuracy to DOM level 3 specification as possible.

keydown keypress beforeInput (insertion) input keyup

Simply triggering the above events does not insert the character into the field, I believe this is standard across most browsers.

So I need to add the character to the e.target's value just before dispatching the input event.

The input event looks (mostly) like this:

  • bubbles: true
  • cancelBubble: false
  • cancelable: true
  • charCode: 0
  • currentTarget: null
  • data: "TEXT I WANT TO PASTE"
  • detail: 0
  • eventPhase: 0
  • keyCode: 0
  • returnValue: true
  • target: input
  • type: "textInput"
  • which: 0

There's no key location value, so I'm not sure where to add the data property to the target!

Is there any data in the keydown events I need to save, and then wait for an immediately following input event? Can I add the data to the input solely based on the information given by input event?

like image 886
alt Avatar asked Oct 20 '22 15:10

alt


1 Answers

Can I add the data to the input solely based on the information given by input event?

Not right now, but the Editing task force currently have a draft spec that extends the InputEvent to allow this via .targetRanges.

As of April 2016 this is far from the implementation stage, as far as I can tell.

Dispatching an event doesn't modify the value of an input

The current thinking, as described in § 3.10. Action versus occurrence of the DOM standard is that:

An event signifies an occurrence, not an action. Phrased differently, it represents a notification from an algorithm and can be used to influence the future course of that algorithm (e.g., through invoking preventDefault()). Events must not be used as actions or initiators that cause some algorithm to start running. That is not what they are for.

This is called out here specifically because previous iterations of the DOM had a concept of "default actions" associated with events that gave folks all the wrong ideas. Events do not represent or cause actions, they can only be used to influence an ongoing one.

This does mean there are a lot of missing APIs in the platform to initiate actions that the browser currently initiates automatically in response to the user's input...

Simulating keypresses is one of such missing features.

like image 177
Nickolay Avatar answered Oct 23 '22 06:10

Nickolay