Skip to content

Instantly share code, notes, and snippets.

@cole007
Created July 7, 2014 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cole007/bc89c34104ffcb00f6b0 to your computer and use it in GitHub Desktop.
Save cole007/bc89c34104ffcb00f6b0 to your computer and use it in GitHub Desktop.
Checkboxify
input[type=checkbox] {
font-size: 24px;
}
a.checkbox {
background: yellow;
}
a.active {
background: red;
}
label {
cursor: pointer;
}
// Shorthand for $( document ).ready()
$(function() {
$('input[type=checkbox]').each(function() {
var thisVal = $(this).val();
var thisId = $(this).prop('id');
var thisName = $(this).prop('name');
var thisCheck = $(this).prop('checked');
$(this).before('<a href="" rel="'+thisId+'" class="checkbox" data-value="'+thisVal+'">Check</a>');
if (thisCheck == true) {
$(this).prev('a').addClass('active');
} else {
$(this).val('');
}
$(this).prop('type','hidden');
});
$('body').on('click','label',function() {
var thisFor = $(this).prop('for');
var thisVal = $('a[rel='+thisFor+']').data('value');
$('a[rel='+thisFor+']').toggleClass('active');
var thisId = $(this).prop('for');
var hidden = $('input#'+thisId);
if ($('a[rel='+thisFor+']').hasClass('active')) hidden.val(thisVal);
else hidden.val('');
});
$('body').on('click','.checkbox',function(e) {
e.preventDefault();
$(this).toggleClass('active');
var thisId = $(this).prop('rel');
var hidden = $('input#'+thisId);
var thisVal = $(this).data('value');
if ($(this).hasClass('active')) hidden.val(thisVal);
else hidden.val('');
});
})
<p>Requires association between for/id pairs</p>
<p>
<label for="checkbox1">Checkbox 1</label>
<input name="checkbox1" id="checkbox1" type="checkbox" checked value="Box"/>
</p>
<p>
<label for="checkbox2">Checkbox 2</label>
<input name="checkbox2[]" id="checkbox2" type="checkbox" checked value="Square"/>
<input name="checkbox2[]" id="checkbox3" type="checkbox" value="Circle"/>
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment