Skip to content

Instantly share code, notes, and snippets.

@codesoda
Created September 28, 2012 10:44
Show Gist options
  • Save codesoda/3799108 to your computer and use it in GitHub Desktop.
Save codesoda/3799108 to your computer and use it in GitHub Desktop.
show/hide text box based on selected drop down
<!--
the select needs
- "has_other" css class
- "data-other" attribute, which points to the id of the element to hide/show (normally a textbox)
- "data-other-text" attribute, which indicates the text which indicates that other has been selected
-->
<select class="has_other" data-other="#textbox_id" data-other-text="...other">
<option>option 1</option>
<option>...other</option>
</select>
<input type="text" id="textbox_id" name="...." placeholder="Enter your own value" />
// handle cases where dropdown's have an "other" option
$.each( $("select.has_other").change(function() {
updateOther(this, true);
}), function() {
updateOther(this);
});
function updateOther(select, focus) {
var $select = $(select);
var $other = $($select.data("other"));
var other_text = $select.data("other-text");
var text = $select.find("option:selected").text();
if (text == other_text) {
$other.show();
if (focus) $other.focus();
} else {
$other.val("").hide();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment