Skip to content

Instantly share code, notes, and snippets.

@nat-n
Created June 16, 2014 15:21
Show Gist options
  • Save nat-n/a062b559521f48e35702 to your computer and use it in GitHub Desktop.
Save nat-n/a062b559521f48e35702 to your computer and use it in GitHub Desktop.
A javascript and styles to implement a new input type which resembles a checkbox but with three arbitrary values instead of just two.
<html>
<head>
<meta charset="UTF-8">
<title>Three Value Toggle</title>
</style>
</head>
<body>
<input name="foo" type="tvg" value="Maybe">
<input name="bar" type="tvg" value="True">
<input name="baz" type="tvg" value="False">
<script>
var toggle_values = ['Maybe', 'True', 'False'];
var tvg_template = '<span></span><input type="text" disabled>';
var tvgs = document.querySelectorAll('input[type=tvg]');
for (var i = 0; i < tvgs.length; i++) {
(function(tvg){
var container = document.createElement('div');
container.className = 'tvg';
var eventmask = document.createElement('span');
var input_wrapper = document.createElement('span');
container.innerHTML = '<div></div>';
container.childNodes[0].appendChild(eventmask);
container.childNodes[0].appendChild(input_wrapper);
tvg.parentElement.replaceChild(container, tvg);
input_wrapper.appendChild(tvg);
if (toggle_values.indexOf(tvg.value)<0) {
tvg.value = toggle_values[0];
}
var j = 0, className;
while (j < toggle_values.length) {
if (toggle_values[j] === tvg.value) {
tvg.className = 'boolean_value_' + String(j);
break;
}
j++;
}
tvg.disabled = true
tvg.type = 'text'
eventmask.addEventListener('click', function(e){
if (tvg.value === toggle_values[0]) {
tvg.value = toggle_values[1];
tvg.className = 'boolean_value_1';
} else if (tvg.value === toggle_values[1]) {
tvg.value = toggle_values[2];
tvg.className = 'boolean_value_2';
} else if (tvg.value === toggle_values[2]) {
tvg.value = toggle_values[0];
tvg.className = 'boolean_value_0';
}
})
})(tvgs[i])
}
</script>
<style>
.tvg {
display: block;
height: 25px;
padding: 2px
}
.tvg div {
position: absolute;
margin: 0;
padding: 0;
height: 21px;
width: 60px;
}
.tvg span:first-child {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.tvg input {
height: 100%;
width: 100%;
border-radius: 10px;
text-align: center;
color: white;
border: 1px solid #999;
}
.boolean_value_0 {background-color: grey}
.boolean_value_1 {background-color: green}
.boolean_value_2 {background-color: red}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment