Adding logic to a page
Attaching custom JS to form

Adding css and javascript to a drupal 8 module

Here's an example of using hook_form_FORM_ID_alter. For this you'll need to make a custom module (conveniently named custommodule in the example below).

Module directory:

custommodule/  
|- js/  
   |-- custommodule.js  
|-- custommodule.info.yml  
|-- custommodule.libraries.yml  
|-- custommodule.module


File contents:


custommodule.info.yml  

type: module
name: Custommodule
description: 'Custom stuff'
package: Custom
core: '8.x'

custommodule.libraries.yml  

custommodule:
  version: 1.x
  js:
    js/custommodule.js: {}
  dependencies:
    - core/jquery

custommodule.module  

&lt;?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custommodule_form_node_article_edit_form_alter(&amp;$form, FormStateInterface $form_state, $form_id) {
  $form['#attached']['library'][] = 'custommodule/custommodule';
}

custommodule.js  

(function($) {

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

      var num1 = $("#edit-field-num-1-0-value").value;
      var num2 = $("#edit-field-num-2-0-value").value;
      var result = (Number(num1)+Number(num2));
      $("#edit-field-num-3-0-value").value = result;
    }
  };

})(jQuery);



The example uses the default article node type, with 3 integer fields (field_num_1, field_num_2, field_num_3), and works on the article edit form (form id -> node_article_edit_form). The js part is also very basic so all it does is set the third field value once the page loads. Drupal_add_js is deprecated, so we use the $form['#attached']['library'] array to attach a library (defined in the custommodule.libraries.yml file) that contains the JS file (a single libraries.yml file can define more libraries, which can include more js/css files).