All files / app/assets/javascripts/behaviors requires_input.js

86.67% Statements 13/15
100% Branches 4/4
80% Functions 4/5
85.71% Lines 12/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                  1x 4x 4x   4x       4x     4x 2x   2x         4x 4x     1x 1x          
import $ from 'jquery';
import { isEmpty } from 'lodash';
import '../commons/bootstrap';
 
// Requires Input behavior
//
// When called on a form with input fields with the `required` attribute, the
// form's submit button will be disabled until all required fields have values.
//
// ### Example Markup
//
//   <form class="js-requires-input">
//     <input type="text" required="required">
//     <input type="submit" value="Submit">
//   </form>
//
 
$.fn.requiresInput = function requiresInput() {
  const $form = $(this);
  const $button = $('button[type=submit], input[type=submit]', $form);
  const fieldSelector =
    'input[required=required], select[required=required], textarea[required=required]';
 
  function requireInput() {
    // Collect the input values of *all* required fields
    const values = Array.from($(fieldSelector, $form)).map((field) => field.value);
 
    // Disable the button if any required fields are empty
    if (values.length && values.some(isEmpty)) {
      $button.disable();
    } else {
      $button.enable();
    }
  }
 
  // Set initial button state
  requireInput();
  $form.on('change input', fieldSelector, requireInput);
};
 
$(() => {
  $('form.js-requires-input').each((i, el) => {
    const $form = $(el);
    $form.requiresInput();
  });
});