BigW Consortium Gitlab

requires_input.js 1.68 KB
Newer Older
1
import _ from 'underscore';
2 3
import '../commons/bootstrap';

4 5 6 7 8 9 10 11 12 13 14 15
// 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>
//
Fatih Acet committed
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 48 49 50 51
$.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 = _.map($(fieldSelector, $form), field => field.value);

    // Disable the button if any required fields are empty
    if (values.length && _.any(values, _.isEmpty)) {
      $button.disable();
    } else {
      $button.enable();
    }
  }

  // Set initial button state
  requireInput();
  $form.on('change input', fieldSelector, requireInput);
};

// Hide or Show the help block when creating a new project
// based on the option selected
function hideOrShowHelpBlock(form) {
  const selected = $('.js-select-namespace option:selected');
  if (selected.length && selected.data('options-parent') === 'groups') {
    form.find('.help-block').hide();
  } else if (selected.length) {
    form.find('.help-block').show();
  }
}

$(() => {
  const $form = $('form.js-requires-input');
52 53 54 55 56
  if ($form) {
    $form.requiresInput();
    hideOrShowHelpBlock($form);
    $('.select2.js-select-namespace').change(() => hideOrShowHelpBlock($form));
  }
57
});