1

The code below does three things...

  1. focuses a text box when it detects the Ctrl + V key press (paste function);
  2. pastes in that box whatever text content is in the clipboard;
  3. lastly, it submits the web form by clicking the submit button.

It works good, with the exception that the JavaScript does not send out the pasted text to the input box variable, as I would like it to do. That variable is empty after submission. You can see that in the URL ("variable="), if you execute the code in your browser.

In short, when I press Ctrl + V, I would like the script to automatically paste and submit whatever text content is in the clipboard.

Can you tell me how to fix this, please?

document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && (event.keyCode == 86)) { // Ctrl + V
    document.getElementById('box').focus();
    document.getElementById('button').click();
  }
});
<form>
  <input id='box' name='variable'>
  <input id='button' type='submit'>
</form>
disinfor
  • 10,865
  • 2
  • 33
  • 44
Alex
  • 85
  • 7

1 Answers1

1

Instead of watching for a key combination that will only work for a subset of users -- not every platform uses Ctrl-V -- watch for the paste event.

'paste' fires before the value hits the box, though, just like 'keydown'. You could reach into the clipboard directly with event.clipboardData.getData(), but that would lose any text that was already in the box before the paste event. Instead I'm using the cheesy but effective method of a quick setTimeout to wait for the pasted value to reach the form field before triggering the submit.

(Triggering the form submit by firing a click event on the submit button like I'm doing here is also a little cheesy, normally I would call the form's submit() method directly.)

let handleSubmit = () => {
  window.setTimeout(() => {
    console.log(document.getElementById('box').value) // <-- proof it worked
    // document.getElementById('button').click() // <-- submit the form
  }, 1)
}

document.getElementById('box').addEventListener('paste', handleSubmit)
<form>
  <input id='box' name='variable'>
  <input id='button' type='submit'>
</form>

(It's probably also worth mentioning that you're substantially changing what would be the normal browser behavior here, and are likely introducing accessibility issues; unless it's very clear to your users that paste will trigger form submit here I would suggest finding a different UX to accomplish this.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53