How to style native input fields with jQuery (no dynamic panels needed)

advanced-prototyping

#1

For a recent project, I had to make sure to actually use checkboxes and style them manually. Because it was not possible to just use dynamic panels or other workarounds, I had to find another solution.

What I did was the following: By placing certain jQuery code in the head of each page, I hid all checkboxes and styled the labels. The same method was valid for radio buttons. I have written a longer blog post as a tutorial with more detailed explanations for the code and how it works. You can find it here: How to style native input fields with jQuery

You can also test it out for yourself: AxShare

If any of you have questions or improvements, please just let me know!


#2

Hi Marcel -

You’d think I’d be able to figure it out from the textfield javascript, but I couldn’t. How would one add hover and focus states to the radio button and checkbox?


#3

No worries, the only way I have gotten it to work is rather complex.

This is line 45-56 from the final code on my blog:

$(‘input[type=radio]’).each(function(){
var radio = $(this);
var label = radio.prev(‘label’);
if(radio.is(’:checked’)){
$(label).css(‘background-color’, ‘#f00’).
css(‘box-shadow’, ‘inset 0px 0px 0px 4px #fff’);
} else {
$(label).css(‘background-color’, ‘#fff’).
css(‘box-shadow’, ‘none’);
}
});

Now add the following lines:

$(‘input[type=radio]’).each(function(){
var radio = $(this);
var label = radio.prev(‘label’);

label.on(‘mouseenter’, function() {
if(radio.is(’:checked’)){
$(label).css(‘background-color’, ‘#00f’).
css(‘box-shadow’, ‘inset 0px 0px 0px 4px #fff’);
} else {
$(label).css(‘background-color’, ‘#00f’).
css(‘box-shadow’, ‘none’);
}
});
label.on(‘mouseleave’, function() {
if(radio.is(’:checked’)){
$(label).css(‘background-color’, ‘#f00’).
css(‘box-shadow’, ‘inset 0px 0px 0px 4px #fff’);
} else {
$(label).css(‘background-color’, ‘#fff’).
css(‘box-shadow’, ‘none’);
}
});

if(radio.is(’:checked’)){
$(label).css(‘background-color’, ‘#f00’).
css(‘box-shadow’, ‘inset 0px 0px 0px 4px #fff’);
} else {
$(label).css(‘background-color’, ‘#fff’).
css(‘box-shadow’, ‘none’);
}
});

The “mouseenter” part gives you the ability to define different hover styles for selected and unselected radio buttons. In the “mouseleave” part, you should switch back to the original styling.

I have put an example online: http://ku6ff2.axshare.com/#c=2

It may be possible to also use :hover for the CSS selector, but so far I haven’t found the right way to do so.


#4

Thanks! I’ll give it a shot.


#5

Moin Moin Marcel!
Is there any chance to send a link to your article once again? You changed your website and it’s not available any longer.

Cheers from Munich :wink:


unlisted #7

closed #8