You can keep it in the onclick
attribute, but it's usually easier to manage broken out into a separate script:
<span>
<input type="checkbox" tabindex="12" value="1" name="salgsvilkar" id="Checkbox2"/>
<label for="Checkbox2">Salgs- og leveringsvilkår er lest og akseptert</label>
</span>
<script type="text/javascript">
document.getElementById('Checkbox2').onclick= function() {
var s= this.parentNode.style;
s.backgroundColor='#E5F7C7';
s.border='solid blue 1px;';
};
</script>
I used this.parentNode
to get the wrapper span around the object being clicked, to remove the need for the extra ID.
Note that since this only detects click, If you click again to unselect the checkbox, the span will still remain highlighted.
Also, don't use XHTML />
self-closing format unless you are actually writing an XHTML document. Unquoted attribute values like tabindex=12
are invalid in XHTML.
re: comment:
But further, what can I do to revert it if it's unclicked?
To make it easier to handle reverting, I'd go to classes:
<style type="text/css">
.highlight {
background: #E5F7C7;
border: solid blue 1px;
}
</style>
...same markup...
<script type="text/javascript">
document.getElementById('Checkbox2').onclick= function() {
var that= this;
setTimeout(function() {
that.parentNode.className= that.checked? 'highlight' : '';
}, 0);
};
</script>
Just removing the class when this
isn't checked
will reset the style to what it was before, without having to remember the old background and border values.
What's the setTimeout
for? Well, when the onclick
event occurs, you've just clicked on the checkbox, and it hasn't toggled its checkedness yet. Indeed, if you return false
you would prevent the checkbox from being changed at all. So we tell the browser to call us back in a tic, after the default action for the checkbox click has occurred. (Consequently, we have to preserve the value of this
, which would be shadowed by a new, useless this
in the timeout function.)
onclick
is really the wrong event to be using here, it should be onchange
. However, you will typically see onclick
used instead because there's a bug in IE where it doesn't fire onchange
until you unfocus the checkbox.