mercredi 15 avril 2015

custom jQuery checkbox allow only one selection

So, the first thing i did was swap out all instances of: checkbox with 'radio' still didn't get my effect.. I want to keep the 'check mark' and custom background of the box etc that this jQuery script allows, everything is perfect, I just need to assure that only ONE ITEM can be checked / selected..


The number one, the jQuery..



/*! custom-checkbox - v1.0.1 */
(function ($) {

$.fn.customCheckbox = function() {

return this.each( function(i,v) {

//Ensure that a checkbox element was passed
if ( !$(v).is(':checkbox') ) {
return false;
}

//Add classes
$(v).addClass("custom-checkbox");

//If not wrapped within label tags, wrap it
var parentLabel = $(v).parent("label");
var withinLabel = parentLabel.length;

if ( !withinLabel ){
$(v).wrap("<label class='custom-checkbox-label'></label>");
}
else {
parentLabel.addClass('custom-checkbox-label');
}

//Create dummy checkbox
var dummy = $("<span class='custom-checkbox-display'></span>");
$(v).after(dummy);
if ( $(v).prop("checked") ) {
$(v).next('.custom-checkbox-display').addClass("checked");
}

//Add/remove classes to checkbox whenever state changes
$(v).change( function(e) {
var checkbox = $(e.currentTarget);
var state = checkbox.prop("checked");
if ( state ) {
dummy.addClass("checked");
}
else {
dummy.removeClass("checked");
}
});

//Make reset button aware of the custom checkboxes
var form = $(v).parents("form");
var reset = form.find("input[type='reset']");
reset.each( function(ri,rv) {
if ( !$(rv).hasClass("custom-checkbox-aware") ) {
$(rv).addClass("custom-checkbox-aware");
$(rv).click( function() {
form.find(".custom-checkbox:checked").trigger("click");
});
}
});

});

};

}(jQuery));


html form mark-up...



<div class="form-group_district">
<p class="label">District Name*</p><br>
<label class="labeldistrict">
<input type="checkbox" name="NYCDistrictName" class="checkboxed" required >
I teach in the New York City Department of Education</label><br>
<label class="labeldistrict">
<input type="checkbox" name="ChiDistrictName" class="checkboxed" required >
I teach in the Chicago Public Schools</label><br>
<label class="labeldistrict">
<input type="checkbox" name="LADistrictName" class="checkboxed" required >
I teach in the Los Angeles Unified School District</label><br>
<label class="labeldistrict">
<input type="checkbox" name="othDistrictName" class="checkboxed" required >
Other</label><br>
<input type="text" name="othDistrictName" maxlength="100" class="otherdistrict" required ><br>
<br>
</div>


For the fiddlers out there.. here is a bare bones demo. just imagine the 'check markup' images were showing on selection / focus. (I don't really want to save them and host them somewhere for this demo).


http://ift.tt/1D1N6ld


Aucun commentaire:

Enregistrer un commentaire