Created
March 4, 2016 17:48
-
-
Save mhulse/a9c2e8bbe26c9f26235f to your computer and use it in GitHub Desktop.
jQuery snippet: Show or hide another element from select option, on change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#foo-other { display: none; } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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