...

View Full Version : Clicking Radio Button Highlights Corresponding Label Text



SteveSensei
08-07-2006, 12:25 AM
I have 2 radio buttons on a form, with text next to each of them. I'd like the text for either radio button to be highlighted (yellow background, maybe) when the corresponding radio button is clicked on so the user can have more feedback as to which button is selected. Is this possible?

JUD
08-07-2006, 01:42 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
// <![CDATA[
function highlight(frm){
var inputs = frm.getElementsByTagName('INPUT');

for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'radio'){
inputs[i].nextSibling.style.backgroundColor = (inputs[i].checked) ? 'yellow' : 'white';
}
}
}
// ]]>
</script>
</head>

<body>
<form>
<input name="radioBtn" type="radio" id="button1" onclick="highlight(this.form)" /><label for="button1">Radio Button 1</label><br />
<input name="radioBtn" type="radio" id="button2" onclick="highlight(this.form)" /><label for="button2">Radio Button 2</label>
</form>
</body>
</html>

glenngv
08-07-2006, 02:03 AM
More efficient solution by looping through all the target radio button group only and not all input elements.

function highlight(objRad){
var radGrp = objRad.form.elements[objRad.name];
for (var i=0; i<radGrp.length; i++){
radGrp[i].nextSibling.style.backgroundColor = (radGrp[i].checked) ? 'yellow' : 'white';
}
}
...
<form>
<input name="radioBtn" type="radio" id="button1" onclick="highlight(this)" /><label for="button1">Radio Button 1</label><br />
<input name="radioBtn" type="radio" id="button2" onclick="highlight(this)" /><label for="button2">Radio Button 2</label>
</form>

SteveSensei
08-07-2006, 02:05 AM
Many thanks for the help from both of you.

Steve



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum