I am creating a small jQuery plugin for my CMS that styles the form input types (radio only, checkbox at the moment). It works by hiding the original form element and placing the normal HTML element (for styling with CSS) in the input location. Then it detects actions on the element and accordingly updates the original input. In addition, it will also work if you click on the appropriate label. Here is my code:
jQuery.fn.ioForm = function() { return this.each(function(){ //For each input element within the selector. $('input', this).each(function() { var type = $(this).attr('type'); //BOF: Radios and checkboxes. if (type == 'radio' || type == 'checkbox') { var id = $(this).attr('id'); checked = ''; if ($(this).attr('checked')) { checked = 'checked'; } //Add the pretty element and hide the original. $(this).before('<span id="pretty_'+ id +'" class="'+ type +' '+ checked +'"></span>'); $(this).css({ display: 'none' }); //Click event for the pretty input and associated label. $('#pretty_'+ id +', label[for='+ id +']').click(function() { if (type == 'radio') { //Radio must uncheck all related radio inputs. $(this).siblings('span.radio.checked').removeClass('checked'); $(this).siblings('input:radio:checked').removeAttr('checked'); //And then check itself. $('#pretty_'+ id).addClass('checked'); $('#'+ id).attr('checked', 'checked'); } else if (type == 'checkbox') { if ($('#'+ id).attr('checked')) { //Checkbox must uncheck itself if it is checked. $('#pretty_'+ id).removeClass('checked'); $('#'+ id).removeAttr('checked'); } else { //Checkbox must check itself if it is unchecked. $('#pretty_'+ id).addClass('checked'); $('#'+ id).attr('checked', 'checked'); } } }); } //EOF: Radios and checkboxes. }); }); };
This works fine for the radio, but the flag seems to get stuck when you click the label flag a second time - the first click on the label successfully changes it to the corresponding state, but pressing the label does not change it again (however, the flag itself still works fine). It works fine in IE8.
I checked the identifier correctly, and it is. I also tried several other methods that I came across to check if the checkbox is checked, but they either gave the same result or failed at all. :(
Any help would be greatly appreciated. Thanks:)
Update Here is the HTML generated by the PHP class. This is after running jQuery and adding span elements:
<div> <p class="label">Test:</p> <span id="pretty_test_published_field" class="checkbox"></span> <input class="checkbox" id="test_published_field" name="test" type="checkbox" value="published"> <label for="test_published_field" class="radio">Published</label> <span id="pretty_test_draft_field" class="checkbox"></span> <input checked="checked" class="checkbox" id="test_draft_field" name="test" type="checkbox" value="draft"> <label for="test_draft_field" class="radio">Draft</label> </div>
source share