diff options
author | Robert Speicher <rspeicher@gmail.com> | 2015-06-24 06:23:25 +0300 |
---|---|---|
committer | Robert Speicher <rspeicher@gmail.com> | 2015-06-27 05:06:42 +0300 |
commit | e4472cee78c1904b801d25d51c14b557afc44816 (patch) | |
tree | ae5ec0b3fcb515ae3958926da7b7a2910f2d55d8 /app/assets/javascripts/behaviors | |
parent | 9f166a864959370d3e31931519506887b902cd11 (diff) |
Add "Requires Input" JS behavior
Diffstat (limited to 'app/assets/javascripts/behaviors')
-rw-r--r-- | app/assets/javascripts/behaviors/requires_input.js.coffee | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/app/assets/javascripts/behaviors/requires_input.js.coffee b/app/assets/javascripts/behaviors/requires_input.js.coffee new file mode 100644 index 00000000000..8318fe435b3 --- /dev/null +++ b/app/assets/javascripts/behaviors/requires_input.js.coffee @@ -0,0 +1,39 @@ +# 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. +# +#= require extensions/jquery +# +# ### Example Markup +# +# <form class="js-requires-input"> +# <input type="text" required="required"> +# <input type="submit" value="Submit"> +# </form> +# +$.fn.requiresInput = -> + $form = $(this) + $button = $('button[type=submit], input[type=submit]', $form) + + required = '[required=required]' + fieldSelector = "input#{required}, select#{required}, textarea#{required}" + + requireInput = -> + # Collect the input values of *all* required fields + 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 + +# Triggered on standard document `ready` and on Turbolinks `page:load` events +$(document).on 'ready page:load', -> + $('form.js-requires-input').requiresInput() |