How to add button to a form that calls custom JavaScript when clicked? I want to create a button on a form that when clicked:


Calls some custom JavaScript
Does not submit the form 


Is this possible with Drupal 8 Forms?
In this example, I've added a custom button action to a Drupal 8 Form. When the button is clicked, it prevents the form from being submitted and allows custom JavaScript to do some work. 

Here are the 3 pieces:


The form button element, with an #attached library
Your custom module's library declaration
The library's .js file


And here is the example code:

in ExampleForm.php

$form['actions']['clear'] = [
  '#type' =&gt; 'button',
  '#value' =&gt; $this-&gt;t('Clear'),
  '#attributes' =&gt; [
    'onclick' =&gt; 'return false;'
  ],
  '#attached' =&gt; array(
    'library' =&gt; array(
      'example/foo',
    ),
  ),
];


example.libraries.yml

foo:
  js:
    js/foo.js: {}


js/foo.js

Drupal.behaviors.example_hello = {
  attach: function (context, settings) {

    // Attach a click listener to the clear button.
    var clearBtn = document.getElementById('edit-clear');
    clearBtn.addEventListener('click', function() {

        // Do something!
        console.log('Clear button clicked!');

    }, false);

  }
};


Don't forget to clear all your caches to ensure your new foo.js library is picked up by Drupal 8.