Stupid Form Tricks - Styling Input Elements Using getAttribute() and Type : text, radio, checkbox, button, submit
for IE5+ and Netscape 6
Traditionally (can we use that word when talking about the web?), the way you applied styles to input elements was like this:
<style> INPUT { background-color: blue; } <style>
This usually worked fine except that it applied to ALL input elements - radio, text, button, etc. After all, the only thing differentiating one input from another was their type attribute. If you wanted each type to have a different look you needed to add style="your style" or class="your class" to each input element.
CSS2
Have you checked out the CSS2 Specs yet? They let you use attributes as selectors. This solves the problem of how to apply different styles to different input types. Using CSS2 you can apply a style only to radio buttons this way:
<style> input[type="radio"] { background-color: blue } <style>
The bad news is that no version of IE supports this CSS2 method. Works great with Netscape 6+ and Mozilla 1.0+ though. Click here to see it in action.
So, how can we achieve this effect in current browsers? That's where the getAttribute() and type come in.
The getAttribute() Solution
getAttribute('type') gives us a way to detect the type of input.
<style> .myRadio { background-color: #ccf } .myCheck { background-color: #fcc } .myText { border: 2px #cfc dotted; font-weight:bold; background-color:#ffc } .myButton { background-color:#f00; color: #fff } .mySubmit { background-color:#fff; border: 2px #c99 dashed } <style>
<script language="javascript"> // -- get all the input elements in the document var x=document.getElementsByTagName('input') for (i=0; i<x.length;i++) { if (x[i].getAttribute('type')=='checkbox') { x[i].className='myCheck'; } if (x[i].getAttribute('type')=='radio') { x[i].className='myRadio'; } if (x[i].getAttribute('type')=='text') { x[i].className='myText'; } if (x[i].getAttribute('type')=='submit') { x[i].className='mySubmit'; } if (x[i].getAttribute('type')=='button') { x[i].className='myButton'; } } </script>
The type Solution
type is another DOM compliant way to distinguish between inputs.
The script is nearly identical to that used with getAttribute() with .type replacing getAttribute().
<script language="javascript"> // -- get all the input elements in the document var x=document.getElementsByTagName('input') for (i=0; i<x.length;i++) { if (x[i].type=='checkbox') { x[i].className='myCheck'; } if (x[i].type=='radio') { x[i].className='myRadio'; } if (x[i].type=='text') { x[i].className='myText'; } if (x[i].type=='submit') { x[i].className='mySubmit'; } if (x[i].type=='button') { x[i].className='myButton'; } } </script>
Remember, place the styles between the head tags and put the script at the bottom of the page (or at the very least, below your form).
Knock yourselves out.
PXL8 2004