1

I am trying to achieve the equivalent of the jQuery (below) written in plain JavaScript:

$('input[name=\"myelementname\"]').keyup();

I haven't been able to find a simple solution thus far. Any ideas?

David Thomas
  • 249,100
  • 51
  • 377
  • 410
user3767692
  • 25
  • 1
  • 6

1 Answers1

9

First you have to create a new Event:

let keyupEvent = new Event('keyup');

And then use EventTarget.dispatchEvent():

// here we use Array.from() to convert the NodeList
// returned from the document.getElementsByNames...
// call into an Array:
Array.from(

  // document.getElementsByName() retrieves all the
  // elements on the page with the supplied name:
  document.getElementsByName('myelementname')

// we iterate over that Array using Array.prototype.forEach():
).forEach(

  // here we use an Arrow function, the 'input' is a reference
  // to the current element (regardless of element-type, since
  // we selected by name) of the Array-element of the Array
  // over which we're iterating.

  // we trigger the named event (using a cached copy of that
  // created Event) on the element:
  input => input.dispatchEvent(keyupEvent)
);

References:

Bibliography:

David Thomas
  • 249,100
  • 51
  • 377
  • 410