Last active
September 20, 2019 05:49
-
-
Save goozler/2c463d081b774fa65c7d to your computer and use it in GitHub Desktop.
JQuery helper for ActiveRecord errors with Bootstrap & SimpleForm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$form = $('form') | |
$formHelper = new FormHelper($form, 'foo') | |
$.ajax | |
type: 'post' | |
url: Routes.foos_path() | |
data: $form.serialize() | |
success: -> | |
$formHelper.clean() | |
$formHelper.reset() | |
error: (xhr) -> | |
res = xhr.responseJSON | |
errors = res.errors | |
$formHelper.clean() | |
$formHelper.errors(errors) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class window.FormHelper | |
constructor: (@form, @model) -> | |
errors: (fieldErrors) -> | |
for field, errors of fieldErrors | |
$formGroup = @form.find('.form-group.' + @model + '_' + field) | |
$formGroup.addClass('has-error') | |
$helpBlock = $formGroup.find('.help-block') | |
if $helpBlock.length == 0 | |
$formGroup.append( | |
$('<span/>', class: 'help-block', text: errors.join(', ')) | |
) | |
else | |
$helpBlock.text(errors.join(', ')) | |
clean: -> | |
@form.find('.form-group').removeClass('has-error') | |
@form.find('.help-block').text('') | |
reset: -> | |
@form.find('input, select, textarea').val('') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment