Skip to content

Instantly share code, notes, and snippets.

@tlinkner
Created November 19, 2014 18:15
Show Gist options
  • Select an option

  • Save tlinkner/9f67d57074a90ba96dac to your computer and use it in GitHub Desktop.

Select an option

Save tlinkner/9f67d57074a90ba96dac to your computer and use it in GitHub Desktop.
Set Classes by Radio Buttons and Checkboxes with JQuery
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radio Classes</title>
<style>
.is-readonly {
color: red;
}
.is-editable {
color: green;
}
.is-template {
color: blue;
}
.is-smallsize {
font-size: .8em;
}
.is-mediumsize {
font-size: 1em;
}
.is-largesize {
font-size: 1.8em;
}
header {
display: none;
background: pink;
}
.is-header header {
display: block;
}
</style>
</head>
<body>
<header>Header</header>
<input type="radio" name="mode" id="m1" value="is-readonly" checked="checked">
<label for="m1">Read</label>
<input type="radio" name="mode" id="m2" value="is-editable">
<label for="m2">Edit</label>
<input type="radio" name="mode" id="m3" value="is-template">
<label for="m3">Template</label>
<hr>
<input type="radio" name="size" id="s1" value="is-smallsize">
<label for="s1">Small</label>
<input type="radio" name="size" id="s2" value="is-mediumsize">
<label for="s2">Medium</label>
<input type="radio" name="size" id="s3" value="is-largesize">
<label for="s3">Large</label>
<hr>
<input type="checkbox" name="header" id="header" value="is-header">
<label for="header">Header</label>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function(){
setRadioClass("input:radio[name=mode]", "body");
setRadioClass("input:radio[name=size]", "body");
setCheckboxClass("input:checkbox[name=header]", "body");
});
setRadioClass = function(radioNameSelector,applyClassSelector) {
$(radioNameSelector).click(function () {
var selectedClass = $(this).val();
var modeClasses = [];
$(radioNameSelector).each(function() {
if ($(this).val() != selectedClass) {
modeClasses.push($(this).val());
}
});
$(applyClassSelector).removeClass(modeClasses.join(' '));
$(applyClassSelector).addClass($(this).val());
});
}
setCheckboxClass = function(checkboxNameSelector,applyClassSelector) {
$(checkboxNameSelector).click(function () {
if(this.checked) {
$(applyClassSelector).addClass($(this).val());
} else {
$(applyClassSelector).removeClass($(this).val());
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment