Skip to content

Instantly share code, notes, and snippets.

@goozler
Last active September 20, 2019 05:49
Show Gist options
  • Save goozler/2c463d081b774fa65c7d to your computer and use it in GitHub Desktop.
Save goozler/2c463d081b774fa65c7d to your computer and use it in GitHub Desktop.
JQuery helper for ActiveRecord errors with Bootstrap & SimpleForm
$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)
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