codecombat/app/core/forms.coffee

54 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2014-01-03 13:32:13 -05:00
module.exports.formToObject = (el) ->
obj = {}
inputs = $('input', el).add('textarea', el)
for input in inputs
input = $(input)
continue unless name = input.attr('name')
obj[name] = input.val()
2014-01-03 13:32:13 -05:00
obj
module.exports.applyErrorsToForm = (el, errors, warning=false) ->
2014-01-03 13:32:13 -05:00
errors = [errors] if not $.isArray(errors)
2014-08-04 13:57:13 -04:00
missingErrors = []
2014-01-03 13:32:13 -05:00
for error in errors
if error.dataPath
prop = error.dataPath[1..]
console.log prop
2014-01-03 13:32:13 -05:00
message = error.message
2014-06-30 22:16:26 -04:00
2014-01-03 13:32:13 -05:00
else
message = "#{error.property} #{error.message}."
message = message[0].toUpperCase() + message[1..]
message = error.message if error.formatted
prop = error.property
2014-06-30 22:16:26 -04:00
2014-08-04 13:57:13 -04:00
missingErrors.push error unless setErrorToProperty el, prop, message, warning
missingErrors
2014-08-04 13:57:13 -04:00
# Returns the jQuery form group element in case of success, otherwise undefined
module.exports.setErrorToField = setErrorToField = (el, message, warning=false) ->
formGroup = el.closest('.form-group')
unless formGroup.length
return console.error el, " did not contain a form group, so couldn't show message:", message
kind = if warning then 'warning' else 'error'
formGroup.addClass "has-#{kind}"
formGroup.append $("<span class='help-block #{kind}-help-block'>#{message}</span>")
module.exports.setErrorToProperty = setErrorToProperty = (el, property, message, warning=false) ->
input = $("[name='#{property}']", el)
unless input.length
return console.error "#{property} not found in", el, "so couldn't show message:", message
setErrorToField input, message, warning
2014-01-03 13:32:13 -05:00
module.exports.clearFormAlerts = (el) ->
2014-01-27 14:30:22 -05:00
$('.has-error', el).removeClass('has-error')
$('.has-warning', el).removeClass('has-warning')
2014-05-30 16:57:21 -04:00
$('.alert.alert-danger', el).remove()
$('.alert.alert-warning', el).remove()
2014-06-30 22:16:26 -04:00
el.find('.help-block.error-help-block').remove()
el.find('.help-block.warning-help-block').remove()