Skip to content

Instantly share code, notes, and snippets.

@rutger1140
Last active March 27, 2018 20:28
Show Gist options
  • Save rutger1140/10b9566d77e00293c935 to your computer and use it in GitHub Desktop.
Save rutger1140/10b9566d77e00293c935 to your computer and use it in GitHub Desktop.
Javascript to toggle field visibility with radio or checkbox form element
$(function(){
var $togglefield = $("[data-toggle-field]");
$togglefield.on("change", function(){
var $this = $(this);
target = $this.data("toggle-field"),
action = $this.data("toggle-action") || 0,
show = false;
// We have a radio
if(action !== 0) {
// Parse action
if (action == "show") {
show = true;
} else {
show = false;
}
// We have a checkbox
} else {
if($this.is(":checked")) {
show = true;
} else {
show = false;
}
}
// Act on show
if(show) {
$(target).show();
} else {
$(target).hide();
}
});
})
<h2>Radio example</h2>
<label>
<input type="radio" name="issues" value="no-issues" data-toggle-field="#describe-issues" data-toggle-action="hide" checked>
I have no issues
</label>
<label>
<input type="radio" name="issues" value="has-issues" data-toggle-field="#describe-issues" data-toggle-action="show">
I had some issues
</label>
<div id="describe-issues" style="display:none">
<p>
Additional form fields with issues
</p>
</div>
<h2>Checkbox example</h2>
<label>
<input type="radio" data-toggle-field="#describe-issues2" value="has-issues">
I have issues
</label>
<div id="describe-issues2" style="display:none">
<p>
Additional form fields with issues
</p>
</div>
@rutger1140
Copy link
Author

TODO:

  • Check for pre-checked checkboxes to inverse show/hide of element
  • Convert into a plugin

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