Skip to content

Instantly share code, notes, and snippets.

@masonjm
Created May 22, 2014 00:43
Show Gist options
  • Save masonjm/1c221475fc099c90ba30 to your computer and use it in GitHub Desktop.
Save masonjm/1c221475fc099c90ba30 to your computer and use it in GitHub Desktop.
Show/Hide form fields based on the value in another field.
(function( $ ){
$.fn.dependsOn = function(element, value) {
var elements = this;
var hideOrShow = function() {
var $this = $(this);
var showEm;
if ( $this.is('input[type="checkbox"]') ) {
showEm = $this.is(':checked');
} else if ($this.is('select')) {
var fieldValue = $this.find('option:selected').val();
if (typeof(value) == 'undefined') {
showEm = fieldValue && $.trim(fieldValue) != '';
} else if ($.isArray(value)) {
showEm = $.inArray(fieldValue, value.map(function(v) {return v.toString()})) >= 0;
} else {
showEm = value.toString() == fieldValue;
}
}
elements.toggle(showEm);
}
//add change handler to element
$(element).change(hideOrShow);
//hide the dependent fields
$(element).each(hideOrShow);
return elements;
};
$(document).on('ready page:load', function() {
$('*[data-depends-on]').each(function() {
var $this = $(this);
var master = $this.data('dependsOn').toString();
var value = $this.data('dependsOnValue');
if (typeof(value) != 'undefined') {
$this.dependsOn(master, value);
} else {
$this.dependsOn(master);
}
});
});
})( jQuery );
@masonjm
Copy link
Author

masonjm commented May 22, 2014

Use it like this:

<select id="picker" name="picker">
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="other">Custom</other>
</select>
<div data-depends-on="#picker" data-depends-on-value="other">
  <label>Custom Value: <input type="text" name="picker_other"/></label>
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment