I’m trying to Show / Hide two elements based on a selection – a label and an input using Javascript getElementsByName. It works with getElementByID if I change things around on the label and input but for some reason Name isn’t working. Here is the code:
<script language="JavaScript" type="text/javascript">
<!--
function Toggle(obj){
var val=obj.value;
if (!obj.m){ obj.m=''; }
if (!obj.m.match(val)){ obj.m+=','+val+','; }
var hide=obj.m.split(',');
for (var zxc0=0;zxc0<hide.length;zxc0++){
if (document.getElementsByName(hide[zxc0])){
document.getElementsByName(hide[zxc0]).style.display='none';
}
}
var show=val.split(',');
for (var zxc1=0;zxc1<show.length;zxc1++){
if (document.getElementsByName(show[zxc1])){
document.getElementsByName(show[zxc1]).style.display='';
}
}
}
//-->
</script>
and here are for form elements:
<div id="styled-select">
<select name="how" onchange="Toggle(this);" class="dropdown">
<option value="Internet Search">Internet Search</option>
<option value="Facebook" >Facebook</option>
<option value="Twitter" >Twitter</option>
<option value="LinkedIN" >LinkedIN</option>
<option value="Referral">Referral</option>
<option value="Other">Other</option>
</select>
</div>
<label name="Referral" style="display:none;">Referred By:</label>
<input name="Referral" style="display:none;" value="" class="hidden-txt">
When the user selects “Referal” it should display the Label and Input named “Referral”. I had this working if I used getElementByID, gave the option two values separated by comma and used seperate IDs for the label and input.
Thank you for your help.
As mentioned by Kevin Boucher, getElementsByName returns an array. Assuming that you want to apply the display=none style to all elements with that name, the code above will achieve that. Also for performance’s sake, the above code only calls document.getElementsByName() once as opposed to the 3+ times above which I’m sure will be beneficial.
It might be worth investigating JQuery for its ease of selecting elements.