Skip to content

Instantly share code, notes, and snippets.

@meleyal
Created May 31, 2013 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meleyal/5684846 to your computer and use it in GitHub Desktop.
Save meleyal/5684846 to your computer and use it in GitHub Desktop.
###
**ConditionalField** toggles the visibility of other elements
based on the state of a form field.
Usage:
<input data-show="#example1" data-unless="blank">
<input data-hide="#example2" data-if="['A', 'B', 'C']">
$('[data-if], [data-unless]').conditionalField()
###
# Class definition
class ConditionalField
constructor: (element, options) ->
@$element = $(element)
@setOptions()
@listen()
# Trigger a change event to set the initial state.
listen: ->
@$element.on 'change keyup', @onChange
@$element.trigger 'change'
# Support both if and unless as conditions.
# Use `.data()` so arrays are parsed for us.
setOptions: ->
{ show, hide, @if, @unless } = @$element.data()
@show = $(show)
@hide = $(hide)
onChange: (e) =>
match = @checkCondition()
@show.toggleClass 'hide', !match
@hide.toggleClass 'hide', match
# Check the input value matches the given condition.
# Matches strings, numbers, or array inclusion.
checkCondition: ->
condition = @if || @unless
val = @$element.val()
condition = '' if condition is 'blank'
match = switch typeof condition
when 'string' then val is condition
when 'number' then parseInt(val) is condition
when 'object' then val in condition
match = !match if @unless
match and !@exceptions()
# TODO: make this an option.
exceptions: ->
@$element.is('#account_vat_id') and $('#account_country').val() is 'Austria'
# Plugin definition
$.fn.conditionalField = (option) ->
this.each ->
$this = $(this)
data = $this.data('conditionalField')
options = typeof option is 'object' && option
$this.data('conditionalField', new ConditionalField(this, options)) unless data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment