BigW Consortium Gitlab

requires_input.js 2.16 KB
Newer Older
1
/* eslint-disable func-names, space-before-function-paren, one-var, no-var, one-var-declaration-per-line, quotes, prefer-template, prefer-arrow-callback, no-else-return, consistent-return, max-len */
2 3 4 5 6
// 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.
//
Fatih Acet committed
7 8
/*= require extensions/jquery */

9 10 11 12 13 14 15 16
//
// ### Example Markup
//
//   <form class="js-requires-input">
//     <input type="text" required="required">
//     <input type="submit" value="Submit">
//   </form>
//
Fatih Acet committed
17 18 19 20 21 22 23 24 25 26
(function() {
  $.fn.requiresInput = function() {
    var $button, $form, fieldSelector, requireInput, required;
    $form = $(this);
    $button = $('button[type=submit], input[type=submit]', $form);
    required = '[required=required]';
    fieldSelector = "input" + required + ", select" + required + ", textarea" + required;
    requireInput = function() {
      var values;
      values = _.map($(fieldSelector, $form), function(field) {
27
        // Collect the input values of *all* required fields
Fatih Acet committed
28 29
        return field.value;
      });
30
      // Disable the button if any required fields are empty
Fatih Acet committed
31 32 33 34 35 36
      if (values.length && _.any(values, _.isEmpty)) {
        return $button.disable();
      } else {
        return $button.enable();
      }
    };
37
    // Set initial button state
Fatih Acet committed
38 39 40 41 42 43 44 45
    requireInput();
    return $form.on('change input', fieldSelector, requireInput);
  };

  $(function() {
    var $form, hideOrShowHelpBlock;
    $form = $('form.js-requires-input');
    $form.requiresInput();
46 47
    // Hide or Show the help block when creating a new project
    // based on the option selected
Fatih Acet committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    hideOrShowHelpBlock = function(form) {
      var selected;
      selected = $('.js-select-namespace option:selected');
      if (selected.length && selected.data('options-parent') === 'groups') {
        return form.find('.help-block').hide();
      } else if (selected.length) {
        return form.find('.help-block').show();
      }
    };
    hideOrShowHelpBlock($form);
    return $('.select2.js-select-namespace').change(function() {
      return hideOrShowHelpBlock($form);
    });
  });
}).call(this);