This form has a hidden textara and a visible textbox. I would like to swap visibility of these elements if option “D:” is selected, but not sure how to correctly check which radio button is checked at any given time:
<script language="JavaScript" type="text/javascript">
function unhide(event) {
event = event || window.event ;
target = event.target || event.srcElement;
if(target.value === "D:") {
if(target.checked) {
document.getElementByName('tarea').style.display='';
document.getElementByName('tbox').style.display='none';
}
}else {
if(target.checked) {
document.getElementByName('tarea').style.display='none';
document.getElementByName('tbox').style.display='';
}
}
}
</script>
</head>
<body>
<form method="get" action="/cgi-bin/form.cgi" enctype="application/x-www-form-urlencoded">
<input type="radio" name="opttype" value="A:" onclick="unhide(event)" />A:
<input type="radio" name="opttype" value="B:" onclick="unhide(event)" />B:
<input type="radio" name="opttype" value="C:" checked="checked" onclick="unhide(event)" />C:
<input type="radio" name="opttype" value="D:" onclick="unhide(event)" />D:
<br><input type="tbox" name="event" />
<br><textarea name="tarea" rows="8" cols="80" style="width:580;height:130;display:none;"></textarea>
Two big things here. First off, you shouldn’t attach your JavaScript event handlers as HTML attributes. Instead, use the “traditional” method (as shown below), or the more “advanced” method.
Second, there’s no need rely on the event object, which will free you from some cross-browser concerns.
Working demo here. Also, make sure the JavaScript code is included after the form or use the
onloadevent.