Last active
March 27, 2018 20:28
-
-
Save rutger1140/10b9566d77e00293c935 to your computer and use it in GitHub Desktop.
Javascript to toggle field visibility with radio or checkbox form element
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(){ | |
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(); | |
} | |
}); | |
}) |
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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: