Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created March 4, 2016 17:48
Show Gist options
  • Save mhulse/a9c2e8bbe26c9f26235f to your computer and use it in GitHub Desktop.
Save mhulse/a9c2e8bbe26c9f26235f to your computer and use it in GitHub Desktop.
jQuery snippet: Show or hide another element from select option, on change.
<select name="foo" id="foo-1">
<option selected value="">Choose …</option>
<option value="Baz">Baz</option>
<option value="Bar">Bar</option>
<option value="Other" data-other="foo-other">Other …</option>
</select>
<div id="foo-other">…</div>
$(function() {
'use strict';
// Show or hide another div based on option selected:
$('select').on('change', function() {
var $this = $(this);
var key = 'other';
var $data = $this.data(key);
var $selected = $this.find(':selected');
var other = $selected.attr('data-' + key);
var $temp;
if (other) {
$temp = $('#' + $selected.data(key))
$this.data(key, $temp);
$temp.show();
} else if ($data) {
$data.hide();
$this.removeData('key')
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment